The principle of JWT

The token is sent back to the server every time the browser makes a request to the server, in order to prevent the user from tampering with the data and encrypt it into a long string.

The detailed steps

1. On the server: The token is created successfully

Create a token string using the third-party module JsonWebToken.

npm i jsonwebtoken
Copy the code

Const JWT = require(‘ jsonwebToken ‘);

const jwt = require('jsonwebtoken'); App. post('/login',(req,res)=>{console.log(' received data is ', req.body) const {name, Password} = req.body if(password === '123456') {// create token // expiresIn: expiration time, in seconds const tokenStr = jwt.sign({name: name }, 'node136', { expiresIn: 10 }); Res. json({MSG :' login succeeded ', } else {res.json({MSG :' failed login '})}})Copy the code

2. On the browser, save the token sent from the backend

localStorage.setItem(‘token’, res.token)

Note :localStorage setItem is used to save getItem is used to get removeItem is removed and exists in the browser, except when the browser is closedCopy the code
$('#btn_login').click(function(){ $.ajax({ type:'post', url:'http://localhost:3000/login', Data: {name: $(' # username). Val (), password: $(' # password). Val ()}, success (res) {the console. The log (' login successfully, token, res token); SetItem ('token', res.token)}})})Copy the code

3. On the browser: Manually carry the token when sending a request

Must be placed in Authorization

/ / in the request header with token $(' # btn_testToken). Click (function () {$. Ajax ({type: "get", url: 'http://localhost:3000/test', headers: { Authorization: localStorage.getItem('token') }, success(res){ console.log(res); }})})Copy the code

4. Server: Implements token authentication

Use express-JWT third party module for identity authentication. As you can see from the module name, this module is specifically designed to work with Express.

Install the third-party plugin NPM I Express-JwtCopy the code

Use of Bearer splices into tokens

const expressJwt = require('express-jwt'); // app.use(jwt().unless()); // JWT () is used to parse tokens and assign data stored in tokens to req.user // Unless () an interface does not require authentication app.use(expressJwt({secret: ['HS256']}). Unless ({path: ['/login'] // All the interfaces in the array need to be authenticated}));Copy the code

When an interface requests to the server, it automatically validates the Authorization field in the request header and does so automatically:

If there are no questions

  1. Assign the data stored in token to req.user
  2. Next ().

If there is a problem, the error next(error message) is thrown.

5. Complementary middleware technology – unified error handling

At the end of all routes, error-handling middleware is added to indicate token errors.

app.use((err, req, res, next) => { if (err.name === 'UnauthorizedError') { // res.status(401).send('invalid token... '); Res.status (401). Send ({status: 1, message: 'Authentication failed! '}); }});Copy the code