Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Trong hướng dẫn này, chúng tôi sẽ xây dựng một Node.js Express đăng nhập và đăng ký API REST API hỗ trợ JWT (JSONWEBETOKEKE) và hoạt động với cơ sở dữ liệu MongoDB bằng cách sử dụng ODM Mongoose. Bạn se biêt:

  • Lưu lượng phù hợp để đăng nhập và đăng ký người dùng với xác thực JWT
  • Node.js Express Architecture với CORS, Xác thực & ủy quyền Middle & Sequelize
  • Cách định cấu hình các tuyến đường Express để làm việc với JWT
  • Cách xác định các mô hình dữ liệu và liên kết để xác thực và ủy quyền
  • Cách sử dụng Mongoose ODM để tương tác với cơ sở dữ liệu MongoDB

Các bài viết liên quan: - Node.js & MongoDB: Ví dụ về mã thông báo làm mới JWT - Ví dụ xác thực ngăn xếp của MERN - Xác thực ngăn xếp trung bình với Angular 8 Ví dụ - xác thực ngăn xếp trung bình Ví dụ-Node.js, Express & MongoDB: Xây dựng một ví dụ API REST CRUD-Hướng dẫn mối quan hệ một-nhiều của MongoDB với các ví dụ Mongoose-MongoDB nhiều-đến nhiều
– Node.js & MongoDB: JWT Refresh Token example
– MERN stack Authentication example
– MEAN stack Authentication with Angular 8 example
– MEAN stack Authentication with Angular 10 example
– MEAN stack Authentication with Angular 11 example
– MEAN stack Authentication with Angular 12 example
– Node.js, Express & MongoDb: Build a CRUD Rest Api example
– MongoDB One-to-Many Relationship tutorial with Mongoose examples
– MongoDB Many-to-Many Relationship with Mongoose examples

Triển khai: Docker Compose: Node.js Express và MongoDB Ví dụ

Nội dung

  • Tổng quan
  • Lưu lượng đăng nhập và đăng ký
  • Node.js Express Đăng nhập với Kiến trúc MongoDB
  • Công nghệ
  • Cấu trúc dự án
  • Tạo Node.js Đăng nhập với ứng dụng MongoDB
  • Thiết lập máy chủ web Express
  • Định cấu hình cơ sở dữ liệu MongoDB
  • Xác định mô hình Mongoose
  • Khởi tạo Mongoose
  • Định cấu hình khóa Auth
  • Tạo các chức năng phần mềm trung gian
  • Tạo bộ điều khiển
    • Bộ điều khiển để đăng ký, đăng nhập, đăng xuất
    • Bộ điều khiển cho phép thử nghiệm
  • Xác định các tuyến đường
  • Chạy & Kiểm tra với kết quả
  • Sự kết luận
  • Đọc thêm
  • Mã nguồn

Tổng quan

Lưu lượng đăng nhập và đăng ký

  • Node.js Express Đăng nhập với Kiến trúc MongoDB
  • Công nghệ

Cấu trúc dự án

Tạo Node.js Đăng nhập với ứng dụng MongoDBThiết lập máy chủ web ExpressĐịnh cấu hình cơ sở dữ liệu MongoDB
Xác định mô hình MongooseKhởi tạo MongooseĐịnh cấu hình khóa Auth
Xác định mô hình MongooseKhởi tạo MongooseĐịnh cấu hình khóa Auth
Xác định mô hình MongooseKhởi tạo MongooseĐịnh cấu hình khóa Auth
Tạo các chức năng phần mềm trung gianTạo bộ điều khiểnBộ điều khiển để đăng ký, đăng nhập, đăng xuất
Tạo các chức năng phần mềm trung gianTạo bộ điều khiểnBộ điều khiển để đăng ký, đăng nhập, đăng xuất
Tạo các chức năng phần mềm trung gianTạo bộ điều khiểnBộ điều khiển để đăng ký, đăng nhập, đăng xuất
Tạo các chức năng phần mềm trung gianTạo bộ điều khiểnBộ điều khiển để đăng ký, đăng nhập, đăng xuất

Lưu lượng đăng nhập và đăng ký

Node.js Express Đăng nhập với Kiến trúc MongoDB

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Công nghệCookies if Client accesses protected resources.

Node.js Express Đăng nhập với Kiến trúc MongoDB

Công nghệ

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Cấu trúc dự ánHTTP request that matches a route will be checked by CORS Middleware before coming to Security layer.

Tạo Node.js Đăng nhập với ứng dụng MongoDB layer includes:

  • Thiết lập máy chủ web Express
  • Định cấu hình cơ sở dữ liệu MongoDB

Xác định mô hình Mongoose

Khởi tạo Mongoose interact with MongoDB Database via Mongoose library and send HTTP response (token, user information, data based on roles…) to Client.

Công nghệ

  • Cấu trúc dự án
  • Tạo Node.js Đăng nhập với ứng dụng MongoDB
  • Thiết lập máy chủ web Express
  • Định cấu hình cơ sở dữ liệu MongoDB
  • Xác định mô hình Mongoose
  • Khởi tạo Mongoose

Cấu trúc dự án

Tạo Node.js Đăng nhập với ứng dụng MongoDB

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Thiết lập máy chủ web Expressconfig

  • Định cấu hình cơ sở dữ liệu MongoDB
  • Xác định mô hình Mongoose

Khởi tạo Mongooseroutes

  • Định cấu hình khóa Auth
  • Tạo các chức năng phần mềm trung gian

Tạo bộ điều khiểnmiddlewares

  • Bộ điều khiển để đăng ký, đăng nhập, đăng xuất
  • Bộ điều khiển cho phép thử nghiệm

Xác định các tuyến đườngcontrollers

  • Chạy & Kiểm tra với kết quả
  • Sự kết luận

Đọc thêmmodels for Mongoose Models

  • user.model.js
  • role.model.js

Mã nguồn

Tạo Node.js Đăng nhập với ứng dụng MongoDB

Thiết lập máy chủ web Express

$ mkdir node-js-express-login--mongodb
$ cd node-js-express-login--mongodb

Định cấu hình cơ sở dữ liệu MongoDB

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes

Xác định mô hình Mongoose
Run the command:

npm install express mongoose cors cookie-session jsonwebtoken bcryptjs --save

Khởi tạo Mongoose

{
  "name": "node-js-jwt-auth-mongodb",
  "version": "1.0.0",
  "description": "Node.js + MongoDB: JWT Authentication & Authorization",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node.js",
    "express",
    "jwt",
    "login",
    "registration",
    "authentication",
    "authorization",
    "mongodb",
    "mongoose"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-session": "^1.4.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.13"
  }
}

Thiết lập máy chủ web Express

Định cấu hình cơ sở dữ liệu MongoDB

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

Xác định mô hình Mongoose
– import

npm install express mongoose cors cookie-session jsonwebtoken bcryptjs --save
1,
npm install express mongoose cors cookie-session jsonwebtoken bcryptjs --save
3 and
npm install express mongoose cors cookie-session jsonwebtoken bcryptjs --save
2 modules:

  • Khởi tạo Mongoose
  • Định cấu hình khóa Auth
  • Tạo các chức năng phần mềm trung gian

Tạo bộ điều khiển
– define a GET route which is simple for test.
– listen on port 8080 for incoming requests.

Hãy nói về mã sau:

app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
  • {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    3: ký và xác minh giá trị cookie. Đặt cookie luôn được ký hợp đồng với
    {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    4, trong khi các khóa khác có giá trị để xác minh, cho phép xoay khóa.
  • {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    5: Chúng tôi không cung cấp
    {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    3, vì vậy chúng tôi sử dụng điều này làm khóa đơn. Trong thực tế, bạn phải cung cấp giá trị dưới dạng biến môi trường bí mật (ví dụ
    {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    7) cho bảo mật.
  • {
      "name": "node-js-jwt-auth-mongodb",
      "version": "1.0.0",
      "description": "Node.js + MongoDB: JWT Authentication & Authorization",
      "main": "server.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [
        "node.js",
        "express",
        "jwt",
        "login",
        "registration",
        "authentication",
        "authorization",
        "mongodb",
        "mongoose"
      ],
      "author": "bezkoder",
      "license": "ISC",
      "dependencies": {
        "bcryptjs": "^2.4.3",
        "cookie-session": "^1.4.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "jsonwebtoken": "^8.5.1",
        "mongoose": "^5.13.13"
      }
    }
    
    8: Chỉ ra rằng cookie chỉ được gửi qua HTTP và không có sẵn cho máy khách JavaScript.

Bây giờ, hãy để chạy ứng dụng với lệnh:

{
  "name": "node-js-jwt-auth-mongodb",
  "version": "1.0.0",
  "description": "Node.js + MongoDB: JWT Authentication & Authorization",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node.js",
    "express",
    "jwt",
    "login",
    "registration",
    "authentication",
    "authorization",
    "mongodb",
    "mongoose"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-session": "^1.4.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.13"
  }
}
9. Mở trình duyệt của bạn bằng URL http: // localhost: 8080/, bạn sẽ thấy:
Open your browser with url http://localhost:8080/, you will see:

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Định cấu hình cơ sở dữ liệu MongoDB

Trong thư mục ứng dụng, tạo thư mục cấu hình cho cấu hình.app folder, create config folder for configuration.

Sau đó tạo tệp db.config.js mới chứa các tham số để thiết lập MongoDB sau:

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};

Xác định mô hình Mongoose

Trong thư mục mô hình, hãy tạo mô hình dữ liệu

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
0 và
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
1 như mã sau:

models/role.model.js/role.model.js

const mongoose = require("mongoose");

const Role = mongoose.model(
  "Role",
  new mongoose.Schema({
    name: String
  })
);

module.exports = Role;

models/user.model.js/user.model.js

const mongoose = require("mongoose");

const User = mongoose.model(
  "User",
  new mongoose.Schema({
    username: String,
    email: String,
    password: String,
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Role"
      }
    ]
  })
);

module.exports = User;

Các mô hình Mongoose này đại diện cho bộ sưu tập người dùng & vai trò trong cơ sở dữ liệu MongoDB. Đối tượng

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
0 sẽ có mảng
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 chứa ID trong bộ sưu tập vai trò làm tài liệu tham khảo.users & roles collections in MongoDB database.
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
0 object will have a
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 array that contains ids in roles collection as reference.

Loại này được gọi là mô hình dữ liệu tham chiếu hoặc chuẩn hóa. Bạn có thể tìm thêm chi tiết tại: Hướng dẫn mối quan hệ một-nhiều của MongoDB với các ví dụ Mongoose
MongoDB One-to-Many Relationship tutorial with Mongoose examples

Sau khi khởi tạo Mongoose, chúng tôi không cần phải viết các chức năng CRUD vì Mongoose hỗ trợ tất cả chúng:

  • Tạo người dùng mới: Object.Save ()
  • Tìm người dùng bằng ID: user.findbyid (id)
  • Tìm người dùng qua email: user.findone ({email: Mạnh})
  • Tìm người dùng theo tên người dùng: user.findone ({tên người dùng: Mạnh})
  • Tìm tất cả các vai trò tên trong mảng
    const express = require("express");
    const cors = require("cors");
    const cookieSession = require("cookie-session");
    
    const app = express();
    
    var corsOptions = {
      origin: "http://localhost:8081"
    };
    
    app.use(cors(corsOptions));
    
    // parse requests of content-type - application/json
    app.use(express.json());
    
    // parse requests of content-type - application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: true }));
    
    app.use(
      cookieSession({
        name: "bezkoder-session",
        secret: "COOKIE_SECRET", // should use as secret environment variable
        httpOnly: true
      })
    );
    
    // simple route
    app.get("/", (req, res) => {
      res.json({ message: "Welcome to bezkoder application." });
    });
    
    // set port, listen for requests
    const PORT = process.env.PORT || 8080;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}.`);
    });
    
    3 đã cho: ricit.find ({name: {$ in: vai trò}}))

Các chức năng này sẽ được sử dụng trong bộ điều khiển và đường giữa của chúng tôi.

Khởi tạo Mongoose

Bây giờ hãy tạo ứng dụng/model/index.js với nội dung như thế này:app/models/index.js with content like this:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const db = {};

db.mongoose = mongoose;

db.user = require("./user.model");
db.role = require("./role.model");

db.ROLES = ["user", "admin", "moderator"];

module.exports = db;

Mở máy chủ.js và thêm mã sau để mở kết nối Mongoose vào cơ sở dữ liệu MongoDB:

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
0

Hàm

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
5 giúp chúng tôi tạo 3 hàng quan trọng trong bộ sưu tập
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3.

Định cấu hình khóa Auth

Các chức năng của JsonWebToken như

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
7 hoặc
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
8 Sử dụng thuật toán cần một khóa bí mật (AS String) để mã hóa và giải mã mã thông báo.
functions such as
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
7 or
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
8 use algorithm that needs a secret key (as String) to encode and decode token.

Trong thư mục ứng dụng/config, hãy tạo tệp auth.config.js với mã sau:app/config folder, create auth.config.js file with following code:

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
1

Bạn có thể tạo chuỗi

{
  "name": "node-js-jwt-auth-mongodb",
  "version": "1.0.0",
  "description": "Node.js + MongoDB: JWT Authentication & Authorization",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node.js",
    "express",
    "jwt",
    "login",
    "registration",
    "authentication",
    "authorization",
    "mongodb",
    "mongoose"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-session": "^1.4.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.13"
  }
}
5 của riêng bạn.

Tạo các chức năng phần mềm trung gian

Để xác minh hành động đăng ký, chúng tôi cần 2 chức năng: - Kiểm tra các bản sao cho

app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
0 và
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
1 - kiểm tra xem
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 trong yêu cầu có hợp pháp hay không
– check duplications for
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
0 and
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
1
– check if
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 in the request is legal or not

middlewares/verifySignUp.js/verifySignUp.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
2

Để xử lý xác thực & ủy quyền, chúng tôi tạo các chức năng sau: - Kiểm tra xem

app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
3 có được cung cấp, hợp pháp hay không. Chúng tôi nhận được mã thông báo từ phiên yêu cầu HTTP, sau đó sử dụng hàm
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
7 của JsonWebToken - kiểm tra xem
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 của người dùng có chứa vai trò cần thiết hay không
- check if
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
3 is provided, legal or not. We get token from HTTP request session, then use jsonwebtoken's
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
7 function
- check if
const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 of the user contains required role or not

middlewares/authJwt.js/authJwt.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
3

middlewares/index.js/index.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
4

Tạo bộ điều khiển

Bộ điều khiển để đăng ký, đăng nhập, đăng xuất

Có 3 chức năng chính để xác thực: -

app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
6: Tạo người dùng mới trong cơ sở dữ liệu MongoDB (vai trò là người dùng nếu không chỉ định vai trò) -
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
7:
-
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
6: create new User in MongoDB database (role is user if not specifying role)
-
app.use(
  cookieSession({
    name: "bezkoder-session",
    // keys: ['key1', 'key2'], 
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);
7:

  • Tìm
    app.use(
      cookieSession({
        name: "bezkoder-session",
        // keys: ['key1', 'key2'], 
        secret: "COOKIE_SECRET", // should use as secret environment variable
        httpOnly: true
      })
    );
    
    0 của yêu cầu trong cơ sở dữ liệu, nếu nó tồn tại
  • So sánh
    app.use(
      cookieSession({
        name: "bezkoder-session",
        // keys: ['key1', 'key2'], 
        secret: "COOKIE_SECRET", // should use as secret environment variable
        httpOnly: true
      })
    );
    
    9 với
    app.use(
      cookieSession({
        name: "bezkoder-session",
        // keys: ['key1', 'key2'], 
        secret: "COOKIE_SECRET", // should use as secret environment variable
        httpOnly: true
      })
    );
    
    9 trong cơ sở dữ liệu sử dụng bcrypt, nếu nó đúngbcrypt, if it is correct
  • Tạo mã thông báo bằng cách sử dụng jsonwebtokenjsonwebtoken
  • Trả về thông tin người dùng và mã thông báo truy cập

-

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
1: Xóa phiên hiện tại.

controllers/auth.controller.js/auth.controller.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
5

Có 4 chức năng: -

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
2 để truy cập công khai -
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3 cho người dùng loggedin (bất kỳ vai trò nào) -
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
4 cho người dùng điều hành -
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
5 cho người dùng quản trị
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
2 for public access
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3 for loggedin users (any role)
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
4 for moderator users
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
5 for admin users

controllers/user.controller.js/user.controller.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
6

Hãy kết hợp các đường giữa với các chức năng của bộ điều khiển trong phần tiếp theo.

Xác định các tuyến đường

Khi khách hàng gửi yêu cầu cho điểm cuối bằng yêu cầu HTTP (nhận, đăng, đặt, xóa), chúng tôi cần xác định cách máy chủ sẽ phản hồi bằng cách thiết lập các tuyến đường.

Chúng tôi có thể tách các tuyến đường của chúng tôi thành 2 phần: để xác thực và cho phép (truy cập các tài nguyên được bảo vệ).

Authentication:

  • Đăng
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    6
  • Đăng
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    7
  • Đăng
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    8

routes/auth.routes.js/auth.routes.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
7

Authorization:

  • Nhận
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    2
  • Nhận
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    3 cho người dùng LoggedIn (người dùng/người điều hành/quản trị viên)
  • Nhận
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    4 cho người điều hành
  • Nhận
    module.exports = {
      HOST: "localhost",
      PORT: 27017,
      DB: "bezkoder_db"
    };
    
    5 cho quản trị viên

routes/user.routes.js/user.routes.js

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
8

Đừng quên thêm các tuyến đường này vào Server.js:

npm init

name: (node-js-express-login--mongodb) 
version: (1.0.0) 
description: Node.js Express + MongoDB: Login and Registration example with Mongoose
entry point: (index.js) server.js
test command: 
git repository: 
keywords: node.js, express, jwt, login, registration, authentication, authorization, mongodb, mongoose
author: bezkoder
license: (ISC)

Is this ok? (yes) yes
9

Chạy & Kiểm tra với kết quả

Chạy ứng dụng Node.js với lệnh:

{
  "name": "node-js-jwt-auth-mongodb",
  "version": "1.0.0",
  "description": "Node.js + MongoDB: JWT Authentication & Authorization",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node.js",
    "express",
    "jwt",
    "login",
    "registration",
    "authentication",
    "authorization",
    "mongodb",
    "mongoose"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "cookie-session": "^1.4.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.13"
  }
}
9.

Bảng điều khiển cho thấy:

npm install express mongoose cors cookie-session jsonwebtoken bcryptjs --save
0

Hãy kiểm tra bộ sưu tập

const express = require("express");
const cors = require("cors");
const cookieSession = require("cookie-session");

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

app.use(
  cookieSession({
    name: "bezkoder-session",
    secret: "COOKIE_SECRET", // should use as secret environment variable
    httpOnly: true
  })
);

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
3 trong cơ sở dữ liệu MongoDB:

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Đăng ký một số người dùng bằng API

const mongoose = require("mongoose");

const Role = mongoose.model(
  "Role",
  new mongoose.Schema({
    name: String
  })
);

module.exports = Role;
5:

  • Quản trị viên có vai trò
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    6
    with
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    6 role
  • Mod với vai trò
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    7 và
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    8
    with
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    7 and
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    8 roles
  • Bezkoder với vai trò
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    8
    with
    const mongoose = require("mongoose");
    
    const Role = mongoose.model(
      "Role",
      new mongoose.Schema({
        name: String
      })
    );
    
    module.exports = Role;
    
    8 role

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Bộ sưu tập

const mongoose = require("mongoose");

const User = mongoose.model(
  "User",
  new mongoose.Schema({
    username: String,
    email: String,
    password: String,
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Role"
      }
    ]
  })
);

module.exports = User;
0 Sau khi đăng ký có thể trông như thế này.

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Truy cập tài nguyên công cộng: Nhận

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
2 GET
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
2

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Tài nguyên được bảo vệ truy cập: Nhận

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3 GET
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Đăng nhập một tài khoản (có mật khẩu sai): Đăng

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
7 POST
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
7

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Đăng nhập bằng tên người dùng và mật khẩu chính xác: Đăng

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
7 POST
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
7

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Bạn có thể kiểm tra cookie với JWT:

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Truy cập các tài nguyên được bảo vệ có tài khoản pháp lý: Nhận

module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3 GET
module.exports = {
  HOST: "localhost",
  PORT: 27017,
  DB: "bezkoder_db"
};
3

Hướng dẫn login node js express + mongodb - nút đăng nhập js express + mongodb

Sự kết luận

Chúc mừng! Hôm nay chúng tôi đã học được rất nhiều điều thú vị về Node.js Express Đăng nhập và đăng ký người dùng với MongoDB và JWT (JsonWebToken) chỉ trong một ví dụ API REST. Bạn cũng biết cách thực hiện ủy quyền dựa trên vai trò để hạn chế quyền truy cập vào các tài nguyên được bảo vệ.

Bạn nên tiếp tục biết cách thực hiện làm mới mã thông báo: Node.js & MongoDB: JWT Làm mới ví dụ về mã thông báo
Node.js & MongoDB: JWT Refresh Token example

Nếu bạn cần một mặt trước làm việc cho phần cuối này, bạn có thể tìm thấy ứng dụng khách trong bài đăng: (chỉ cần thay đổi lưu trữ cục bộ thành cookie) - Vue - Angular 8 / Angular 10 / Angular 11 / Angular 12 / Angular 13 - React / React Hook / React Redux JWT Ví dụ xác thực
(just change Local Storage to Cookies)
- Vue
- Angular 8 / Angular 10 / Angular 11 / Angular 12 / Angular 13
- React / React Hooks / React Redux JWT Authentication example

Học hỏi! Hẹn gặp lại.

Đọc thêm

  • https://www.npmjs.com/package/express
  • http://expressjs.com/en/guide/routing.html
  • Giới thiệu chuyên sâu về mã thông báo web jwt-json
  • https://mongoosejs.com/docs/queries.html
  • https://mongoosejs.com/docs/api/model.html

FullStack: - Mevn: Vue + Node.js + Express + MongoDB Ví dụ - có nghĩa là:
- MEVN: Vue + Node.js + Express + MongoDB example
- MEAN:

  • Angular 8 + Node.js + Express + MongoDB Ví dụ
  • Angular 10 + Node.js + Express + MongoDB Ví dụ
  • Angular 11 + Node.js + Express + MongoDB Ví dụ
  • Angular 12 + Node.js + Express + MongoDB Ví dụ
  • Angular 13 + Node.js + Express + MongoDB Ví dụ

- MERN: React + Node.js + Express + MongoDB Ví dụ

Triển khai: Docker Compose: Node.js Express và MongoDB Ví dụ

Mã nguồn

Bạn có thể tìm thấy mã nguồn đầy đủ cho hướng dẫn này trên GitHub.