JWT

A Token,

  • What is a Token?

    Token refers to the credential for accessing resources and is a method of identity authentication. It is the most popular method for cross-domain authentication.

  • Why Token?

    In the past, it was popular to use session for identity authentication. Session is to save session data in the server for identity authentication, which will lead to excessive server pressure in high concurrency. In addition, if it is a server cluster, the session sharing of these servers is required.

    Token does not store session data on the server, but on the client. The Token is stored in each HEADERS request, and the server checks whether the Token is valid and can access resources.

  • The difference between traditional tokens and JWT

    • The traditional Token

      The user initiates a login request, returns the Token and saves the Token in the database. The user needs to carry the Token when accessing resources, and the server compares the Token with the database.

    • JWT

      A user initiates a login request and returns a Token, but the Token is not stored in the database. The user needs to carry the Token when accessing resources. After obtaining the Token, the server verifies the validity of the Token.

Ii. Implementation process of JWT

  • The JWT consists of header, payload, and Verify Signature

  • header

    It contains the signature algorithm and Token type, and is converted into a string using the Base64URL algorithm

    // Plaintext example:
    {
        "alg":"HS256"."typ":"JWT"
    }
    Copy the code
  • payload

    It contains JWT standard data and custom data, which is then converted into a string using the Base64URL algorithm

    Common JWT standard data are:

    • Iss: Provider.
    • Sub: subject, usually a user ID.
    • Exp: indicates the expiration time.
    • Iat: creation time.
    • Jti: Unique identifier of the token.

    The above standard data can be used optionally

    // Plaintext example:
    {
      "id": 3."name": "Bmongo"."age": 18."iat": 1588139323."exp": 1588139333
    }
    Copy the code

    Note: Since JWT is not encrypted by default, do not store sensitive information here

  • verify signature

    This part is the signature of the first two parts to prevent data tampering

    Secret is the key saved by the server and known only by the server. Then, use the signature algorithm specified in the header to sign the above two parts and generate the signature according to the following formula

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

    Once you’ve worked out the signature, go through the three parts. Just split it and return it to the user

    JWT examples:

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTAsIm5hbWUiOiLlvKDkuIkiLCJhZ2UiOjE2LCJpYXQiOjE1ODgxMzkzMjMsImV4cCI6MTU4ODE zOTMzM30.WzZp_aNgiw4iTsX7buxMhZe0z0e94Ve6ImEZ8L8L78cCopy the code
  • Client request

    Each request from the client requires this token, usually by writing the token to the headers of the request

Node.js

JWT is used in Node.js

1. Start using

Token generation and verification are accomplished through the NPM package JsonWebToken

npm install --save jsonwebtoken
Copy the code
2. Generate and verify the Token
const jwt = require("jsonwebtoken")
// Add salt to encrypt
const secret = '113Bmongojsdalkfnxcvmas'

/ / token is generated
// Info payload is the information that needs to be stored in tokens
function createToken(info) {
	let token = jwt.sign(info, secret, {
        //Token validity time unit: s
		expiresIn:60 * 60 * 10
	})
	return token
}

/ / authentication Token
function verifyToken(token) {
	return new Promise((resolve, reject) = > {
		jwt.verify(token, secret, (error, result) = > {
            if(error){
                reject(error)
            } else {
                resolve(result)
            }
		})
	})
}
Copy the code
Use 3.
const express = require("express")
const app = express()
const jwt = require("jsonwebtoken")
// Add salt to encrypt
const secret = '113Bmongojsdalkfnxcvmas'
const user = {
	id:10.name:"Bmongo".age:16,}/ / token is generated
// Info payload is the information that needs to be stored in tokens
function createToken(info) {
	let token = jwt.sign(info, secret, {
        //Token validity time unit: s
		expiresIn:60 * 60 * 10
	})
	return token
}

/ / authentication Token
function verifyToken(token) {
	return new Promise((resolve, reject) = > {
		jwt.verify(token, secret, (error, result) = > {
            if(error){
                reject(error)
            } else {
                resolve(result)
            }
		})
	})
}

// Set to allow cross-domain
app.use(function(req, res, next) {
    // specify that other domains are allowed to access * all
	res.setHeader("Access-Control-Allow-Origin"."*");
    // Allow the client to request headers with
	res.setHeader("Access-Control-Allow-Headers"."Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    // The type of request allowed
	res.setHeader("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
	res.setHeader("X-Powered-By".'3.2.1')
    // Make the options request return quickly
	if(req.method=="OPTIONS") res.send(200);
	else  next();
});

/ / white list
const whiteList = ['/login']

app.use((req,res,next) = > {
	if(! whiteList.includes(req.url)) { verifyToken(req.headers.authorization).then(res= > {
			next()
		}).catch(e= > {
			res.status(401).send('invalid token')})}else {
		next()
	}
})

app.post('/login'.(req,res) = > {
	let token = createToken(user)
	res.json({token})
})

app.get("/api/info".(req,res) = > {
	res.send({
		result:1.data: {"name":"Bmongo"."id":1}})})Copy the code

The original link