Json Web Token (JWT) is a JSON-based development standard (RFC 7519) implemented for the transfer of declarations between network application environments. The token is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios in distributed sites. The JWT declaration is generally used to pass authenticated user identity information between the identity provider and the service provider to obtain resources from the resource server, and to add some additional declaration information necessary for other business logic. The token can also be used directly for authentication or can be encrypted.

Related technical points

eggmiddleware

JWT’s official website

node-jsonwebtoken

The installation

npm install jsonwebtoken
Copy the code

Middleware Programming

Create a new jwt.js file under the Middleware file

'use strict'
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken'Jsonwebtoken Module. Exports = (options, app) => {return async function userInterceptor(ctx, next) {
    letAuthToken = ctx.header.authorization // Obtain the authorization in the headerifSubstring (7) const res = verifyToken(authToken) // Decrypted obtained Tokenif(res.corpid && res.userid) {// If you need to restrict single-end login or disable a token during use, or change the permission of the token. Const redis_token = await app.redis. Get () const redis_token = await app.redis.'loginToken').get(res.corpid + res.userid) // Obtain the saved tokenif (authToken === redis_token) {
          ctx.locals.corpid = res.corpid
          ctx.locals.userid = res.userid
          await next()
        } else {
          ctx.body = { code: 50012, msg: 'Your account has been logged in elsewhere'}}}else {
        ctx.body = { code: 50012, msg: 'Login status expired'}}}else {
      ctx.body = { code: 50008, msg: 'Please log in and try again.'}}}} // Decrypt and verifyfunction verifyToken(token) {
  const cert = fs.readFileSync(path.join(__dirname, '.. /public/rsa_public_key.pem') // Public keylet res = ' '
  try {
    const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {}
    const { exp } = result,
      current = Math.floor(Date.now() / 1000)
    if (current <= exp) res = result.data || {}
  } catch (e) {
    console.log(e)
  }
  return res
}
Copy the code

Using middleware

Add the following configuration in config.default.js to enable and configure the middleware

// Use middleware config. Middleware = ['jwt' ]

config.jwt = {
	enable: true,
	ignore: [ '/api/v1/test/'.'/public/'Exports = app => {const JWT = app.middleware.jwt(); app.router.get('/api/v1/test/', jwt, app.controller.test.test);
};
Copy the code

Token is generated

You are advised to write it in the helper for easy invocation

loginToken(data, expires = 7200) {
  const exp = Math.floor(Date.now() / 1000) + expires
  const cert = fs.readFileSync(path.join(__dirname, '.. /public/rsa_private_key.pem'Const token = jwt.sign({data, exp}, cert, {algorithm: const token = jwt.sign({data, exp}, cert, {algorithm:'RS256' })
  return token
}
Copy the code

Call the token generation method

const token = ctx.helper.loginToken({ corpid: usersData.corpid, userid: Usersdata.userid}, 7200) // token generates await app.redis. Get ('loginToken').set(usersData.corpid + usersData.userid, token, 'ex'// Save to redis ctx.body = {data: {token, expires: this.config.login_token_time}, code: 1, MSG:'Login successful'} // return to the front endCopy the code

Front end use

Set headers Authorization = ‘Bearer ‘+ Token Bearer with Spaces

Example: / / request in axios interceptor service. The interceptors. Request. Use (config = > {if (store.getters.token) {
    config.headers['Authorization'] = `Bearer ${getToken()}`}return config
}, error => {
  console.log(error)
  Promise.reject(error)
})
Copy the code

Use Openssl to generate the private key public key

Create git path \bin and git path \usr\bin. Create git path \usr\bin. C: Program Files\Git\bin and C: Program Files\Git\usr\bin Generate public key: openssl genrsa -out rsa_private_key. openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

END

Welcome to my blog