Implementation of JWT identity authentication mechanism

(1) First, let’s understand the limitations of the session authentication mechanism

 (2) What is JWT

The full name of JWT is JSON Web Token, which is currently the most popular cross-domain authentication solution

(3) The working principle of JWT (important!!!)

 (4) Components of JWT

 (5) The meaning of each component of JWT

 (6) How to use JWT

 (7) Use of JWT in Express

 

 

 The following unless is used to specify which interfaces do not require access rights. For example, the following ones that start with /api do not require access rights and can be accessed directly.

 

 app.js code:

// 导入express模块
const express = require('express');
// 创建wen服务器
const app = express();
// 导入JWT相关的两个包
// 用户生成jwt的包
const jsonwebtoken = require('jsonwebtoken');
// 用于将客户端发送过来的jwt字符串解析成json对象的包
const expressJWT = require('express-jwt')
// 导入允许跨域资源共享的包
const cors = require('cors');
// 将跨域资源共享的包注册为全局中间件
app.use(cors());
// 解析 POST 提交过来的表单数据
app.use(express.urlencoded({ extended: false }))
// 1.定义secret密钥
const secretkey = 'sy no1---';
// 注册将jwt字符串还原成json对象的中间件 unless后面的部分代表以/api开头的都不需要访问权限
// 只要配置成功了express-jwt这个中间件,就可以把解析出来的用户信息挂载到req.user属性上
app.use(expressJWT({ secret: secretkey, algorithms: ['HS256'], }).unless({ path: [/^\/api\//] }))
    // 登录接口
app.post('/api/login', (req, res) => {
        // 将请求体的数据转换存在userinfo中
        const userinfo = req.body;
        if (userinfo.username !== 'sy' || userinfo.password !== '123456') {
            return res.send({ status: 400, msg: '登录失败' });
        }
        // 生成jwt字符串:jwt.sign()方法接收三个参数,分别是用户信息对象、加密密钥、配置对象(配置当前token的有效期)
        // 记住:千万不要把密码加密到token字符串中
        const tokenstr = jsonwebtoken.sign({ username: userinfo.username }, secretkey, { expiresIn: '30s' })
            // 登录成功的时候调用jwt.sign()方法生成jwt字符串,并通过token属性发送给客户端
        res.send({ status: 200, msg: '登录成功!', token: tokenstr });
    })
// 这是一个有权限的api接口
app.get('/admin/getinfo', (req, res) => {
        res.send({
            status: 200,
            message: '获取用户信息成功!',
            data: req.user //要发送给客户端的信息
        })
    })
    // TODO_06:使用全局错误处理中间件,捕获解析 JWT 失败后产生的错误
app.use((err, req, res, next) => {
    // 这次错误是由 token 解析失败导致的
    if (err.name === 'UnauthorizedError') {
        return res.send({
            status: 401,
            message: '无效的token',
        })
    }
    res.send({
        status: 500,
        message: '未知的错误',
    })
})
app.listen(80, () => {
    console.log('hahaha');
})

start server

First initiate a post request

 

You will get a returned token

 

Copy this token and initiate a get request, add the authorization attribute and value in the header, the value is the token, but you must add Bearer in front to get the result as shown in the  figure: iat and exp do not care about it, they are used to control the validity period of the token .

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/127322119