JSON Web Tokens with Express.js

Tạo folder project:

mkdir express_jwt
cd express_jwt
npm init -y

install the Express framework:

npm install --save express

Cài đặt nodemon

npm install -g nodemon

install the body-parser middleware to parse the JSON body from the HTTP request:

npm i --save body-parser jsonwebtoken

Test server express:
Edit file index.js

const express = require('express');
const app = express();

app.listen(3000, () => {
    console.log('Authentication service started on port 3000');

Run project:

nodemon index.js

Cấu hình module

const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

Tạo file config.js với nội dung:

const tokenKey='';
module.exports = {

accessTokenSecret This is your secret to sign the JWT token
Tạo user data

const users = [
    username: "hai",
    password: "123",
    role: "admin",
    username: "vinh",
    password: "123",
    role: "member",

Edit file index.js

Mở postman truy cập http://localhost:3000/login để tạo token key

Sau khi co token key thì các bạn thêm vào trong file config.js

Books Service
Tạo file books.js
Tạo data:

const books = [
        "author": "Chinua Achebe",
        "country": "Nigeria",
        "language": "English",
        "pages": 209,
        "title": "Things Fall Apart",
        "year": 1958
        "author": "Hans Christian Andersen",
        "country": "Denmark",
        "language": "Danish",
        "pages": 784,
        "title": "Fairy tales",
        "year": 1836
        "author": "Dante Alighieri",
        "country": "Italy",
        "language": "Italian",
        "pages": 928,
        "title": "The Divine Comedy",
        "year": 1315

Tạo Express middleware

const authenticateJWT = (req, res, next) => {
    const authHeader = req.headers.authorization;

    if (authHeader) {
        const token = authHeader.split(' ')[1];

        jwt.verify(token, accessTokenSecret, (err, user) => {
            if (err) {
                return res.sendStatus(403);

            req.user = user;
    } else {

Tạo route get data

app.get('/books', authenticateJWT, (req, res) => {

File books.js

Run service book

nodemon books.js

Test http://localhost:4000/books

Link source code in here
Nguồn tham khảo:https://stackabuse.com/authentication-and-authorization-with-jwts-in-express-js/