I. Installation package file

npm install jsonwebtoken --save

Jsonwebtoken can be used to create tokens

const jwt = require('jsonwebtoken')
	/ / create a token
let token = jwt.sign(obj,secret,opt)
	/ / decoding token
let payload = jwt.verify(token,secret)
Copy the code

Implementation approach

The login process

When we received the account password check from the front desk, we created the token and returned it to the client

const police = require(".. /.. /.. /model/police");
	const jwt = require('jsonwebtoken')
	 
	let myPolice = new police(); 
	let {secret} =  require('.. /.. /.. /util/secret.js')
	 
	async function login(ctx, next) {
	  let postData = ctx.request.body
	  let selectResult = await myPolice.checkLogin(postData)
	  if (selectResult.err) {
	    ctx.body = {
	      status: 1.message: err
	    }
	  } else if(! selectResult.result) { ctx.body = {status: 1.message: 'User does not exist'}}else if (selectResult.result[0].password ! == postData.password) { ctx.body = {status: 1.message: 'Password error'}}else {
	    // The account password is correct
	    // Payload Write some values. Time: creation date timeout: How long will it take to expire
	    let payload = {userNumber:postData.userNumber,time:new Date().getTime(),timeout:1000*60*60*2}
	    let token = jwt.sign(payload, secret);
	    ctx.body = {
	      status: 0.message: 'Login successful'.data:{
	        token
	      }
	    }
	  }
	}
	 
	module.exports = login
Copy the code

Payload Parameter

Iss: issued tosub: User-orientedaud: Receiver IAT (Issued at): issue time exp(Expires): expiration time NBF (not before) : cannot be accepted before JTI: JWT ID Provides a unique identifier for a Web token. Example: {"sub":"subject"."aud":"sina.com"."iss":"baidu.com"."iat":1528360628."nbf":1528360631."jti":"253e6s5e"."exp":1528360637}
Copy the code

JWT. Sign (object, key)

The two parameters are the signature algorithm and the user-defined signature Key (salt). Signature keys can be passed in the form of byte[], String, or key. The first two forms are stored in the Builder’s keyBytes property, and the latter in the Builder’s key property. If it is a second (and String) key, it is base64 decoded for byte[].

Iii. How to verify token

1, create,checkToken.jsFile middleware

1. Token decryption method 1

const jwt = require('jsonwebtoken')
	async function check(ctx, next) {

	    let url = ctx.url.split('? ') [0]
	    
	    // There is no need to verify the token if the login page and registration page are used
	    if (url === '/admin/user/login' || url === '/admin/user/register') {
	        await next()
	    } else {
	
	        // Otherwise, the token is obtained
	        let token = ctx.request.headers["authorization"]
	
	        if (token) {
	
	            // Start parsing if there is a token
	            const tokenItem = jwt.verify(token, 'token')
	            // Structure the creation time and expiration time of the token
	            const { time, timeout } = tokenItem
	            // Get the current time
	            let data = new Date().getTime();
	            If the current time minus the token creation time is less than or equal to the token expiration time, the token has not expired. Otherwise, the token has expired
	            if (data - time <= timeout) {
	                // Token does not expire
	                await next()
	            } else {
	                ctx.body = {
	                    status: 405.message:'Token has expired, please log in again'
	                }  
	            }
	        }
	    }
	}

	module.exports = checkToken
Copy the code

2. Token decryption method 2

	const Promise = require("bluebird");
	const jwt = require("jsonwebtoken");
	const verify = Promise.promisify(jwt.verify);
	let { secret } = require(".. /util/secret");
	 
	async function check(ctx, next) {
	  let url = ctx.request.url;
	  // Log in without checking
	  if (url == "/users/login") await next();
	  else {
	      // specify the token to be written in header 'autohrization'
	    let token = ctx.request.headers["authorization"];
	    / / decoding
	    let payload = await verify(token,secret);
	    let { time, timeout } = payload;
	    let data = new Date().getTime();
	    if (data - time <= timeout) {
	        / / not expired
	      await next();
	    } else {
	        / / overdue
	      ctx.body = {
	        status: 50014.message:'Token has expired'}; }}}module.exports = check
Copy the code

4. Register for use in the app.js entry

const checkToken = require('./middleware/checkToken.js')
	
// Validate token middleware functions
	
app.use(checkToken)
Copy the code