JWT authentication mechanism
What is the JWT
JSON Web Token is the most popular cross-domain authentication solution
How JWT works
Summary: The user information is saved in the client browser in the form of Token strings. The server authenticates the user by restoring the Token strings.
Component of JWT
A JWT consists of three parts: Header, Payload, and Signature. Use the English “between the three.” The format is as follows
Header.Payload.Signature
Copy the code
- Payload part
That's the real user information
, which is a string generated after user information is encrypted. - The Header and Signature
Safety correlation
Only to ensure the security of Token
How JWT is used
When the client receives the JWT returned by the server, it usually stores it in localStorage or sessionStorage. Thereafter, each time the client communicates with the server, it takes this JWT string with it for authentication. The recommended practice is to place JWT in the Authorization field of the HTTP request header in the following format:
Authorization:Bearer <token>
Copy the code
- Install jWT-related packages
Run the following command to install the following two JWt-related packages:
npm install jsonwebtoken express-jwt
Copy the code
Among them:
- Jsonwebtoken is used to generate JWT strings
- Express-jwt is used to parse JWT strings back to JSON objects
- Import the jWT-related packages
// Import express module
const express = require('express')
// Create a server instance for Express
const app = express()
// Install and import the two jWt-related packages
const jwt = require('jsonwebtoken')
const expressJWT = require('express-jwt')
// Allow cross-domain resource sharing
const cors = require('cors')
app.use('cors()')
Copy the code
- Define secret the secret key
To ensure the security of JWT strings and prevent them from being cracked during network transmission, we need to define a secret key for encryption and decryption
- When generating a JWT string, the secret key is used for user information
encrypted
, resulting in an encrypted JWT string - When parsing JWT strings back to JSON objects, use the secret key
decryption
// Secret is a string of characters
const secretKey = 'yiquersanli(~ ▽ ~)/'
Copy the code
4. Generate a JWT string after successful login. Invoke the sign() method provided by the JSONWebToken package to encrypt user information into a JWT string and respond to the client
app.post('/api/login'.(req,res) = >{
// Dump the data in the req.body request body as the userinfo constant
const userinfo = req.body
// Login failed
if(userinfo.username ! = ='admin'|| userinfo.password! = ='0000000') {return res.send({
status:400.message:'Login failed! '})},// Successful login
// After the user logs in successfully, the JWT. Sign () method is called to generate a JWT string. The token is sent to the client
// Parameter 1: the user's information object
// Parameter 2: encryption key
// Parameter 3: configuration object. You can configure the validity period of the current token in seconds and hours
// Note: Do not encrypt the password into the token string
const tokenStr = jwt.sign({username:userinfo.username},secretKey,{expiresIn:'30s'})
res.send({
status:200.message:'Successful landing'.// Call jwt.sign() to generate a JWT string with three parameters: user information object, encryption key, token expiration date
token:tokenStr,// The token string to be sent to the client})})Copy the code
- Restore the JWT string to a JSON object
Each time the client accesses any authorized interface, it needs to send the Token string to the server through the Authorization field in the request header for identity authentication. At this point, express-JWT middleware can be used in the server to automatically parse and restore the Token sent by the client into JSON objects:
// Use app.use () to register middleware
//expressJWT({secret:secretKey}) is the middleware used to parse tokens
//.unless({path:[/^/ API \//]}) to specify which interfaces do not need access
//path:[/^/ API \//]: all interfaces starting with/API/do not require permissions to access
app.use(expressJWT(secret:secretKey).unless({path: [/^\/api\//]}))
Copy the code
- Use req.user to obtain user information
When the express-JWT middleware configuration is successful, the user information parsed from the JWT string can be accessed using the req.user object in those interfaces that have access to it
- Catch errors that occur when parsing JWT fails
When using Express-JWT to parse the Token string, if the Token string sent by the client is expired or invalid, a parsing failure error will be generated, affecting the normal operation of the project. This error can be caught and handled using Express’s error middleware
app.use((err,req,res,next) = >{
// Error caused by token parsing failure
if(err.name === 'UnauthorizedError') {return res.send({status:401.message:'Invalid token'})}// Error caused by other reasons
res.send({status:500.message:'Unknown error'})})Copy the code