There are three plugins, plus the front end for a total of at least four plugins

>>>>>> Back-end application: Jsonwebtoken // passport // key resolution rule plug-in, Has a key analysis -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > > > > > > for use in the front-end of JWT - decode / / no key, The secretOrKey is stored in an environment variable, so keyless resolution must be used on the front end.Copy the code

Use jsonWebToken for encryption and use JWT keyless resolution

Const JWT = require(const JWT = require('jsonwebtoken'); Const jwt_decode = require('jwt-decode'); // Set a key const secretOrKey ="hello world"; // Const rules = {id:'0001', name: 'liyuanzhe', job: 'developer'}; New promise ((resolve, resolve, => {// jwt.sign is performed asynchronously // create string using jsonWebToken // parameter (need to encrypt the content, key string, token attribute, Jwt. sign(rules, secretOrKey, {expiresIn: 3600}, (err, token) => {if (err) throw err;
        
        token = "Bearer "+ token /* As requested by the plugin author, we must write Bearer space */ console.log(token); / / print the generated token string / / Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. EyJpZCI6IjAwMDEiLCJuYW1lIjoibGl5dWFuemhlI iwiam9iIjoiZGV2ZWxvcGVyIiwiaWF0IjoxNTU3Mzk3ODYwLCJleHAiOjE1NTc0MDE0NjB9.fT4eKuvAbvH66QM frSHEm1UmeHPedYOWYIr3rNwAPg8 // Res.send (token) the actual development sends to the front-end resolve(token); }); }). Then ((token) => {//shiyong jwt-decode decode tokens without keys console.log(jwt_decode(token)); // {id:'0001', name: 'liyuanzhe', job: 'developer', // iat: 1557397860, exp: 1557401460 } // iat : // exp: expiration time // the front-end should parse the string, then localStorage, sessionStorage, // send the token string to the backend when the network request is sent,})Copy the code

The back-end resolves the tokens sent to the front-end with keys

The Passport // Token resolution main plug-in acts as a container for the various Passport policies

Passport – JWT // Key resolution rule (policy) plug-in with key resolution

Take this as an example:

// * // Passport has the concept of a strategy. A strategy is a small number of reservation methods that are executed before the request reaches the actual route. If your strategy determines that a request is illegal, the route will not be implemented. Instead, 401 Unauthorized. // */ const express = require('express'); const server = express(); Const bodyParser = require(const bodyParser = require('body-parser');
server.use(bodyParser.urlencoded({ extended: false})); server.use(bodyParser.json()); server.listen(8080); const router = express.Router(); Const passport = require(const passport = require('passport'); // Initialize passpor server.use(passport. Initialize ()); // JWT strategy const JwtStrategy = require('passport-jwt').Strategy; // ExtractJwt const ExtractJwt = require('passport-jwt').ExtractJwt; // Set policy options 1. Key 2. Token extraction methodletOpts = {// Obfuscated key stored in environment variable secretOrKey:"hello world"JwtFromRequest; // Define the token data extracted from the request header Authrization: ExtractJwt. FromAuthHeaderAsBearerToken ()} / / var jwtConfig = new JwtStrategy construction strategy objects (opts, (jwt_payload, Next) => {// Jwt_payload is the same token string as jwt-decode. Log (jwt_payload) // Db_user.findById (jwt_paypay.id){//. Then (user => {//return done(null, the user) / /}). The catch (err = > {/ / console log (err) / /}) / / / /} to test we have no the pituitary step next (null, jwt_payload)}); Use (jwtConfig); // passport.authenticate("Encryption Algorithm Strategy", verify condition, callback) router.get('/testJWT', passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({ ok: 1 })
})
server.use('/test', router);
Copy the code

Testing:

Data:

{ id: ‘0001’, name: ‘liyuanzhe’, job: ‘developer’}

Front-end generation token:

Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAwMDEiLCJuYW1lIjoibGl5dWFuemhlIiwiam9iIjoiZGV2ZWxvcGVyIiwiaWF0IjoxNTU3NDA 0NzE1LCJleHAiOjE1NTc0MDgzMTV9.jqwwdAH4qKFCX7t0xHJ0YXiprNmlSpM0sDc8PwoWSbc

Parse tokens using jwt-decode:

{ id: ‘0001’, name: ‘liyuanzhe’, job: ‘developer’, iat: 1557404715, exp: 1557408315 }

Use postman tests

Enter a valid token:

Conclusion:

Server Passport Passport – JWT

Three layers of nested use

Server.use (passport. Use (new passport-jwt.Strategy(// policy options {secretOrKey:"hello world",jwtFromRequest: ExtractJwt. FromAuthHeaderAsBearerToken ()}, / / callback function (jwt_payload, next) = > {next (null, Jwt_payload)}))) / / -- -- -- -- -- - > using partial / / passport. The authenticate ("jwt", verify condition, callback) router.get('/testJWT', passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({ ok: 1 })
})

server.use('/test', router);
Copy the code