The use of JWT authentication mechanism based on express in nodejs, the use of jsonwebtoken package and express-jwt middleware, and the middleware of token interception

1. Components of JWT

JWT通常由三部分组成,分别是 Header(头部)、Payload(有效荷载)、Signature(签名)。
    三者之间使用英文的“.”分隔,格式如下:
        Header.Payload.Signature

2. The meanings of the three parts of JWT

    JWT的三个组成部分,从前到后分别是 Header、Payload、Signature。
        其中:
            Payload部分才是真正的用户信息,它是用户信息经过加密之后生成的字符串。
            Header和Signature是安全性相关的部分,只是为了保证Token的安全性。

3. How to use JWT

    客户端收到服务器返回的JWT之后,通常会将它储存在localStorage或sessionStorage 中。
    此后,客户端每次与服务器通信,都要带上这个WT的字符串,从而进行身份认证。推荐的做法是把JWT放在HTTP请求头的Authorization字段中,格式如下:
        Authorization: Bearer <token>

Key points to note: When generating Token strings, be sure to remove passwords and avatars that have security risks.
1. Run the following command to install the package that generates Token strings:

npm i jsonwebtoken@8.5.1

2. In the header area of ​​the module that sends the token js file, import the jsonwebtoken package:

const jwt = require('jsonwebtoken')

3. Create a config.js file and share the jwtSecretKey string of encrypted and restored Tokens
. After the jwt update on July 7, 2020, the installed express-jwt module will default to version 6.0.0, and the updated jwt needs to be in the configuration Add the algorithm attribute, that is, set the algorithm of jwt. Generally, HS256 is the default value for configuring algorithms:

//我这里版本比较低不用配置algorithms
module.exports = {
    
    
  jwtSecretKey: 'itheima No1. ^_^',
}

4. Encrypt the user information object into a Token string

// 导入配置文件
const config = require('../config')

// 生成 Token 字符串
const tokenStr = jwt.sign(user, config.jwtSecretKey, {
    
    
  expiresIn: '10h', // token 有效期为 10 个小时
})

5. Respond to the generated Token string to the client

res.send({
    
    
  status: 0,
  message: '登录成功!',
  // 为了方便客户端使用 Token,在服务器端直接拼接上 Bearer 的前缀
  token: 'Bearer ' + tokenStr,
})
  1. Configure middleware for parsing Token

1. Run the following command to install the middleware for parsing Token:

npm i express-jwt@5.3.3

2. Before registering the route in app.js, configure the middleware that parses the token:

// 导入配置文件
const config = require('./config')

// 解析 token 的中间件
const expressJWT = require('express-jwt')

// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({
    
     secret: config.jwtSecretKey }).unless({
    
     path: [/^\/api\//] }))

3. In the error level middleware in app.js, capture and process the error after Token authentication fails

// 错误中间件
app.use(function (err, req, res, next) {
    
    
  // 省略其它代码...

  // 捕获身份认证失败的错误
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败!')

  // 未知错误...
})

In this way, you have successfully set up the token and token verification interception.
If the authentication is successful in the request, you can use req.user to get the information of the user encapsulated in the token *

Guess you like

Origin blog.csdn.net/weixin_45822938/article/details/123256503