Learning Koa is not easy. Today I learned KOA-JWT, the middleware essential for login verification. This article explains what JWT is, how tokens come from, and how to verify tokens. Out of the ordinary, code first! (This code is generated by KoA-Generater, install koA-JWT, jSONWebToken two NPM packages)

File name and source code:















File name: routes/index.js



This simply mimics a login request and returns a token.



File name: routes/users.js



/usersThe following routes require JWT authentication to access


File name: auth.js





Ideas and Instructions:

localhost:3000/login














authorization
'Bearer token'
IsRevoked Returns true indicating that the token is incorrect and false indicating that the token is correct.



jsonwebtoken.verify





API resolution:







secret



passthrough



isRevoked





Jsonwebtoken: This is the hero!

Jsonwebtoken. sign(payload, secretOrPrivateKey, [options, callback]) generates a tokenCopy the code

1. Payload is the data that needs to be encrypted. There are three keys in the payload: IAT (issued at), exp (expiresIn), and NBF (notBefore). These parameters are recommended to be written in options, not in payload. 2. The secretOrPrivateKey can be a string, encrypted key, or asymmetrically encrypted private key. 3. Options can choose parameters is much better here, the algorithms: encryption algorithm, the default is HS256, expriesIn: token effective duration, notBefore: token when failure, more parameters refer to the website; 4. Return a token.


Jwt. verify(token, secretOrPublicKey, [options, callback]) verify a tokenCopy the code

1.tokenThe token is generated by the sign function.

2.secretOrPublicKey: corresponds to the encryption factor that generates the token. It is either the same string and the symmetric encryption key, or the asymmetric encryption public key.

3.options: Mirror and agree with sign.Audience, Issuer, jwTIDAnd so on.

4. If the payload is correct, it returns a payload. If the error message is incorrect, throw an Err.



There is a pit in the document:

expiredIn: The default unit isSeconds!!!!!! Here’s the hard evidence (jsonwebtoken/verify.jsHere is the comparison in seconds, don’t think of it as milliseconds





We also use a token in the cookie, so that each request can be authenticated by the token. We can ignore autherization (passthrough: true) in the header.