This article aims to implement encrypted (MD5) JWT functionality with Express for login authentication with minimal code.

JWT – JSON Web Token

JWT(JSON Web Token) is an open jSON-based standard implemented to pass declarations between network application environments. JWT declarations are generally used to pass authenticated user identity information between the identity provider and the service provider in order to obtain resources from the resource server. For example, for user login.

JWT data structure

There are three parts of the JWT: the JWT header, payload, and signature.

JWT head

The JWT header section is a JSON object that describes the JWT metadata, usually as follows.

{

“Alg” : “HS256”,

“Typ” : “JWT”

} In the above code, the alG attribute represents the algorithm of the signature. The default is HMAC SHA256 (written as HS256); The TYp attribute represents the type of the token, and the JWT token is written as JWT.

Effective load

The Payload part is also a JSON object that stores the data that needs to be transmitted. JWT specifies seven official fields to choose from.

Iss (Issuer) : exp (expiration time) : expiration time sub (subject) : aud (audience) : NBF (Not Before) : iAT (Issued At) : Issue time JTI (JWT ID) : Number In addition to this, you can also customize fields such as:

{
  "sub": "1234567890"."name": "John Doe"."admin": true
}
Copy the code

The signature

The Signature section is a Signature to the first two sections, preventing data tampering.

First, you need to specify a secret. This key is known only to the server and cannot be disclosed to users. Then, using the signature algorithm specified in the Header (HMAC SHA256 by default), generate the signature as follows.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
Copy the code

After calculating the Signature, add the Header, Payload, and Signature parts into a string, and use dots (.) between each part. Delimit, and it can be returned to the user.

JWT working process

Working process: 1. The front-end sends the user name and password to the server.

2. The server generates the JWT.

3. Send the generated JWT to the front end, and relevant data (such as user role, login time, etc.) will be saved in the current session.

4. When the front end requests data from the server, it adds the JWT to the Header and sends it to the server.

5. The server receives the JWT and verifies the user information.

6. If the authentication is successful, data is returned to the front-end.

Express implementation process

Express part

2, set password salt value and token secretKey (JWT is not encrypted by default, MD5 is used here, and salt is used to complex the password)

// /constant.js var crypto = require('crypto'); Module.exports = {MD5_SUFFIX: 'houyuping', // constant length salt md5: function (PWD) {var md5 = crypto.createHash('md5'); return md5.update(pwd).digest('hex'); }, secretKey: 'yichen_qingting_jwttoken' };Copy the code

3. Generate tokens during login

// /routes/user.js var token = jwt.sign(data, constant.secretKey, { expiresIn: Json ({success: true, message: 'success', token: token})Copy the code

4. Set up middleware that intercepts tokens, including token verification and return of error messages:

// /jwt.js const expressJwt = require("express-jwt"); const secretKey = require('./constant'); // The Express-JWT middleware automatically does token validation and error handling for us, so generally we can write in the format without any problem, where unless puts the API that you want not to check the token. const jwtAuth = expressJwt({secret: secretKey.secretKey}).unless({path: ["/users/login","/users/query"]}); module.exports = jwtAuth;Copy the code

5. Finally, put JWT middleware in front of routing middleware

var express = require('express'); var router = express.Router(); Var jwtAuth = require('./ JWT '); Use (function (req, res, next) {console.log('this is an API request! '); // Pass it to the next middleware, noting that the middleware registers next() in order; });Copy the code

Front-end 1. Save the obtained token to localStorage

let token = window.localStorage.getItem("wyg_token");
Copy the code

2. Add the token to the header for each request

This. $axios. Post (' http://127.0.0.1:3000/users/modifyPwd '{data: data}, {headers: {' Authorization' : `Bearer ${token}`}} )Copy the code

JWT pros and cons

Advantages:

  1. It is not easy to be attacked and has high security
  2. The Authorization header is used to transfer tokens without cross-domain problems
  3. The extra information is stored on the client, the server does not occupy many resources, and there is no session sharing problem

Disadvantages:

  1. Login status information renewal problem. Once a token is issued, the cancellation cannot be modified during the expiration period.
  2. It takes up more memory than cookies.