Nodejs login generates token and verifies it

Table of contents

1. Basic concepts

2. JTW

3. Practice


 1. Basic concepts

"token": is a general term that refers to a data structure used to represent identity, permissions, or access credentials. It can be a string, number, or other form of data.

The main purpose:

  1. Authentication: During the authentication process, the user provides credentials (such as username and password), and the server verifies the validity of the credentials and issues an authentication token to the user. This token can be a long-term persistent token, or a short-term temporary token used to prove the user's identity in subsequent requests.

  2. Authorized access: When the user is authenticated, the server can issue an access token to the user. This token is used to prove that the user has been granted specific permissions or access to specific resources. The user uses the token in subsequent requests to access protected resources, and the server verifies the token's validity and permissions.

  3. API access: In application development, API tokens are often used to authorize third-party applications or services to access specific APIs. The developer registers the application with the API provider and obtains an API token to authenticate and authorize the application to access and use the functionality and data provided by the API.

To put it simply, it is a credential for this login . As long as you bring the token returned by the server, you can access the current corresponding content (the specific content needs to be determined by the server).

2. JTW

The token itself is an encrypted string, but when generated by yourself, security, encryption algorithm, etc. need to be considered, but we can use plug-ins such as jsonwebtoken to help us tokenize and verify.

Install jsonwebtoken

npm install jsonwebtoken

Generate token 

Syntax: JWT.sign(data, encrypted string, time)  

const JWT = require("../../utils/JWT.js")

let token = JWT.sign({ username:'奥特曼',id:123 },'secret', '1day')

Verification token 

Syntax: jwt.verify (generated token, encrypted string)

jwt.verify(token,'secret')

3. Practice

 encapsulation


const jwt = require('jsonwebtoken')
const secret = "ultraman"//解密密钥

const JWT = {
    createToken: (data,time) => { 
        return jwt.sign(data,secret,{expiresIn:time})
    },
    verifyToken: (token) => { 
    // 如果token过期或验证失败,将返回false
       try {
        return jwt.verify(token,secret)
       } catch (error) {
        return false
       }
    }
}

module.exports = JWT

Login interface

 login: async (req, res, next) => { 
        var result = await UserService.login(req.body)
        if (result.length) {
            // 生成token
            const DeepRes = JSON.parse(JSON.stringify(result[0])) 
            delete DeepRes.password
            let token = JWT.createToken({ username: req.body.username,id:result[0]._id }, '1day')
            res.header('Authorization', token)
            res.send({code:200,msg:'登录成功',data:{token,userInfo:DeepRes}})
        } else {
            res.send({code:500,msg:'账号或密码错误'})
        }
        console.log(result,'登陆了');
    },

Verification interception

Interception was used in the verification, in the form of Bearer xxxx, so only the token part was intercepted for verification.

app.use((req, res, next) => {  
  if (whiteList.includes(req.path)) return next()

  let token = req.get('Authorization')
  if (token) {
    const result = JWT.verifyToken(token.split(' ')[1])
    if (result) {
      next()
    } else {
      res.status(401).send({ code: 401, msg: '登录信息已失效,请重新登录' })
    }
  } else { 
    res.send({ code: 500, msg: '未携带token' })
  }
  
})

After verification, the data will be returned, and the token can be generated and passed to the data at that time. With the data, we can obtain the user information by ourselves.

Token gets personal information

  getUserInfo: async (req, res, next) => { 
        let token = req.get('Authorization')
        const info = JWT.verifyToken(token.split(' ')[1])
       const userInfo =  await UserService.getProfile(info.id)
        console.log(userInfo, 'userInfo');
        res.send({code:200,msg:'获取成功',data:{userInfo:userInfo[0]}})
    }

 

Guess you like

Origin blog.csdn.net/m0_46846526/article/details/132189929