Token-based authentication – JWT simply says that after the user logs in to the interface, the server returns a token, and the front-end takes the token and puts it in the header. Each time the request is sent to the server, the server authenticates according to the token. If the request is valid, the server continues to authenticate, and if it is invalid, the server returns immediately.

  • Generate tokens using JsonWebToken
  • Verify that the token is invalid with Express-JWT
  • Use JsonWebToken to parse out the user information in the token, such as id

NPM install jsonWebToken –save NPM install Express-jwt

The server/node_api/ SRC /libs/token.js file is added

import jwt from 'jsonwebtoken' import config from '.. /config' const jwtSecret = process.env.NODE_ENV === 'production' ? config.tokenKey.prod : config.tokenKey.dev export const generateToken = (userName, userId) => { return new Promise((resolve, reject) => { const token = jwt.sign({userName,userId}, jwtSecret, {expiresIn: '24h'}); resolve(token) }) } export const getToken = (token) => { return new Promise((resolve, reject) => { if(! token) { reject({error: 'Token is empty '})}else {console.log('token=',token) const info = jwt.verify(token.split(' ')[1], JwtSecret) console.log('info=',info) resolve(info) // Resolve returned value}})}Copy the code

Jwt.sign () passes in the value to be parsed, usually userName, userId, expiresIn sets the expiration time of the token. Print the following:

token= bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6ImFkbWluIiwidXNlcklkIjoxLCJpYXQiOjE2MDk3NDExNDEsImV4cCI6MTYwOTgyNzU0MX0.JsioftQnZxM5xkfTkAiUjmzW29XGbkx2_H69-xe-iYs
info= { userName: 'admin', userId: 1, iat: 1609741141, exp: 1609827541 }
Copy the code

Add a middleware to app.js to validate token expiration.

app.use((req, res, next) => { const token = req.headers['authorization'] if(token == undefined) { next() }else { getToken(token).then((data) => { res.data= data; next() }).catch((error) => { next() }) } }) app.use(expressJwt({ secret:'Baohong123456', algorithms: ['HS256'] }).unless({ path: ['/users/login'] })) app.use('/', indexRouter) app.use('/users', usersRouter) ... Use (function (err, req, res, next) {// set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} / / render the error page res. Status (err) status | | 500) if (err) status = = = 401) {res. Status (401). The send (' token failure ')} res.render('error') })Copy the code

Edit server/node_api/ SRC /routes/users.js to generate a token for the user after successful login. Because Node does not directly query the database, but calls the login interface provided by Java, if the return is normal, the login is considered successful

router.post('/login', (req, res, next) => {
  login({ user_name: 'admin', user_pwd: '666' }).then(result => {
    const { result: { data: { data: { user, token } } } } = { result }
    generateToken(user.userName,user.id).then(nodeToken => {
      res.send({
        token,
        user,
        nodeToken
      })
    })
  })
})
Copy the code

After successfully calling the login interface, the front-end will get the returned token, which can be stored in localStorage, and put the token in the request header each time the request is sent. src/libs/axios.js

const token = localStorage.getItem('token')
if(token){
  config.headers.authorization = 'Bearer '+token
}
Copy the code

See node.js express for token verification