1. Generate token jwt passport to generate and verify tokens
jsonwebtoken
1. Installation
npm i jsonwebtoken
2. Introduce
const jwt = require('jsonwebtoken')s
3. Define rules
const rule = {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> id: result[0].id, name: result[0].name }
Since id, name and name are obtained through the database, this method is used
4. Setting method/generating token
("rule", "Encrypted Name", "Expiration time", "Arrow function")
(rule, , { expiresIn: 3600 }, (err, token) => { if (err) return return ({ code: 1, msg: `Bearer ${token}` }) })
The rule here is the verification rule mentioned above, which is the encryption name, but it is encapsulated to the outside. ExpiresIn:3600 means 3600 seconds. The generated token returned by msg
5. Verify token
// $router get api/user/current // @desc return current user // @access private ("/current", "Verify Token", (req, res) => { ({ code: 1, msg: 'Verification is successful' }) })
We need to verify the token in "Verify Token"
2. Verify the Token using passpport-jwt||passport
passport
passport-jwt
1. Installation
npm install passport-jwt npm i passport
2. Use
This is an example method that was excerpted from npm
passport
(new LocalStrategy( function(username, password, done) { ({ username: username }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } if (!(password)) { return done(null, false); } return done(null, user); }); } ));
The methods in this method can be deleted and write your own business logic. I use mysql, so there is no method used
Initialize passport
(());
passport-jwt
new JwtStrategy(options, verify)
3. Actual use
(Project entrance file)
const passport = require("passport") //Configure and reference in the entry file//Initialize passport(()); require("./config/passport")(passport)
Here we separate the passport configuration file, and the passprot introduced above is introduced.
config/
const db = require("../db/index") const JwtStrategy = require('passport-jwt').Strategy const ExtractJwt = require('passport-jwt').ExtractJwt const key = require("../config/key") const opts = {} = (); = ; = passport => { (new JwtStrategy(opts, (jwt_payload, done) => { // { id: 1, name: 'wz', iat: 1660299838, exp: 1660303438 } (jwt_payload); sqlcc = `SELECT * FROM user WHERE id=${jwt_payload.id};` (sqlcc, (err, result) => { (result[0]); if (err) { return done(null, ) } if ( != 0) { return done(null, result[0]) } else { return done(null, false) } }) })); }
Note that the generated token should have a unified format. A correct token should be like this
Bearer ${token}
, note the space between Bearer and the generated token.
Next, verify the token in the place where verification is required
// $router get api/user/current // @desc return current user // @access private ("/current", ("jwt", { session: false }), (req, res) => { ({ code: 1, msg: }) })
If the verification token passes, it will be executed
The method in the process, jwt_jpayload will output the result. After obtaining the result, we use id to query the data in the User table, and then get it through (database table name).
// { id: 1, name: 'wz', iat: 1660299838, exp: 1660303438 } (jwt_payload);
2. express-jwt || jsonwebtoken generation token verification token installation
npm install jsonwebtoken express-jwt
Noticejsonwebtoken is used to generate JWT strings
express-jwt is used to parse Jwt strings into JSON objects
Create a new folder config/
= { keyOringe: "secret" }
Expose the set key value
Introduce where needed
const jwt = require("jsonwebtoken")
if (password == (results[0].password)) { //If successful, pass 1 and the page will be transferred to vue+ const rule = { + id: results[0].id, + adminname: results[0].adminname + } + const tokenstr = (rule, , { expiresIn: 3600 }) + ({ code: 1, msg: 'Login successfully', + token: tokenstr }) }
- Call the () method to generate a JWT string and send it to the client through the token attribute
- Parameter 1: User information object
- Parameter 2: Encrypted key
- Parameter 3: Configuration object You can configure the validity period of the current token
- Rule is just taken away, but it is okay to write it directly.
Use in middleware
const { expressjwt: jwt } = require("express-jwt") const key = require('../config/key') (jwt({ secret: , algorithms: ["HS256"], }).unless({ path: ["/admin/login", "/admin/register"] }) )
Then use the private interface to access
//$route GET admin/banner/ //@desc Modify the carousel diagram interface('/', (req, res) => { (req); ({ code: 1, msg: 'Get user information successful', data: }) })
This will return the token with user information!
Capture errors generated after parsing JWT failed
When parsing a Token string using express-jwt, if the token string sent by the client isExpiredorIllegal, will produce aAnalysis failedThe error affects the normal operation of the project and can be passedExpress error middleware, catch this error and perform related processing, the sample code is as follows:
//Define error middleware after all routes//Use global error handling middleware to capture errors generated after parsing JWT failure((err, req, res, next) => { //Judge whether it is caused by the Token parsing failure if ( == 'UnauthorizedError') { return ({ status: 401, message: 'Invalid Token' }) } ({ status: 500, message: 'Unknown error' }) })
Summarize
This is the end of this article about the two ways to configure token verification. For more related to configure token verification, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!