background

On the NodeJS Web Server project, we need to do login authentication, and exchanging the user name and password for token is a common way.

The relevant knowledge

This section describes the JSON Web Token (JWT)

It is a TOKEN format for JSON representation. A token contains three parts: header, payload, and signature. The header is the part of the token and stores the type and encoding of the token. Base-64 encoding is usually used. Payload contains information. You can store any kind of information, such as user information, product information, etc. They are stored using base-64 encoding. Signature contains a mixture of header, payload, and key. Signature must be securely stored on the server. Website: https://tools.ietf.org/html/rfc7519 (content) {" iss ":" Online JWT Builder ", "iat:" 1416797419, "exp" : 1448333419, "aud": "www.example.com", "sub": "[email protected]", "GivenName": "Johnny", "Surname": "Rocket", "Email": "[email protected]", "Role": ["Manager", "Project Administrator"]} * iss: the issuer of this JWT, whether to use it is optional; * sub: The user for which the JWT is intended, whether to use it or not is optional; * AUD: The party receiving the JWT, whether to use it is optional; * EXP (Expires): When expires, here is a Unix timestamp, whether to use it is optional; * IAT (Issued at): When issued (UNIX time), use optional; * NBF (Not Before) : If the current time is Before the time in the NBF, the Token is Not accepted; There is usually some leeway, like a few minutes; , whether to use is optional;Copy the code

Jsonwebtoken introduction

It is an implementation of JWT’s NodeJS.

use

Install the class library

npm install jsonwebtoken
Copy the code

The import

var jwt = require('jsonwebtoken');
Copy the code

code

const TokenUtil = { sign: function(userName){ const payload = { userName }; var token = jwt.sign(payload, privateKey); console.log(`token = ${token}`); return token; }, verify: function(token){ var decoded = jwt.verify(token, privateKey); // console.log('decoded = '+decoded); console.log('decoded = '+JSON.stringify(decoded)); }, main: function(){ let str = this.sign('zhang3'); this.verify(str); }}Copy the code

Official website: github.com/auth0/node-…

Reference:

Github.com/auth0/node-… Tools.ietf.org/html/rfc751… Blog.csdn.net/github_3563… www.cnblogs.com/xiekeli/p/5…