jwt authentication mechanism

jst usually consists of three parts, namely header (head), payload (payload), signatrue (signature)

Separate the three with commas:

Header.Payload.Signatrue
  • payload is the real user information part, it is an encrypted string
  • header and signatrue are security-related parts

Install:

npm install jsonwebtoken express-jwt

  • jsonwebtoken is used to generate jwt string
  •  express-jwt is used to parse and restore jwt strings into json objects
// 导入用于生成的 jwt 字符串的包
const jwt = require('jsonwebtoken')
// 导入用于将客户端 发送过来的 jwt 字符串,解析还原成 json 对象 的包
//const expressJWT = require('express-jwt')
const { expressjwt } = require("express-jwt") //@7版本

Define the secret key

In order to ensure the security of the jwt key and prevent the jwt string from being cracked during network transmission, we need to define a secret key for encryption and decryption:

  • When generating the jwt string, you need to use the secret key to encrypt the user information, and finally get the encrypted jwt
  • To parse and restore the jwt string into a json object, you need to use the secret key to decrypt
// secret 的本质就是一个字符串
const secretKey =‘^_^’

Generate jwt string after successful login

Call the sign() method provided by the jsonwebtoken package to encrypt the user's information into a jwt string and respond to the client.

app.get('/login',(req,res)=>{
  //调用 jwt ,sign(),生成 jwt 字符串,三个参数分别是:用户信息对象,加密密钥,配置对象
  res.send({
    status:200,
    msg:'成功',
    data:req.query,
    token:jwt.sign({
      username:'Bearer ' + req.body.username
    },secretKey,{
      expiresIn:'30s'
    })
  })
}),

Restore jwt string to json object 

Every time the client accesses those authorized interfaces, it needs to actively send the Token string to the server for identity authentication to the Authorizaction in the request header.

At this point, the server can automatically parse and restore the Token sent by the client into a json object through the intermediate key of express-jwt

// 使用 app.use() 来注册中间件  express-jwt @7
// expressJWT({secret:secretKey}) 就是用来解析 Token的中间件
//  用来指定那些借口不需要访问权限
app.use(
  jwt({
    secret: "shhhhhhared-secret",
    algorithms: ["HS256"],
  }).unless({ path: ["/token"] })
);

Note: As long as express-jwt is configured successfully, you can hang the parsed user information on the req.user property 

Guess you like

Origin blog.csdn.net/Cat_LIKE_Mouse/article/details/124916148