1. About JWT
-
JWT(JSON Web Token) is an open jSON-based standard implemented to pass declarations between network application environments.
-
JWT declarations are typically used to pass authenticated user identity information between the identity provider and the service provider to facilitate resource retrieval from the resource server. For example, for user login.
2. Composition of JWT
The first part is called the header, the second part is called the payload, and the third part is the signature.
-
header
The header of the JWT carries two pieces of information:
-
Declare type, in this case JWT
-
Algorithms that declare encryption usually use HMAC SHA256 directly
-
The complete header looks like this JSON:
{
typ: "JWT",
alg: "HS256"
}
Copy the code
-
playload
The payload is where the useful information is stored. The name seems to refer specifically to the cargo carried on the plane, and this valid information consists of three parts
-
A declaration of registration in a standard
-
Public statement
-
Private declaration
-
-
signature
The third part of the JWT is a visa information, which consists of three parts:
-
Header (Base64)
-
Payload (base64)
-
secret
This part is used by the base64-encrypted header and the Base64-encrypted payload. A string of concatenated strings, salted with the encryption declared in the header, and then formed the third part of the JWT:
49UF72vSkj-sA4aHHiYN5eoZ9Nb4w5Vb45PsLF7x_NY
The secret key is stored on the server. The server generates token and authentication based on the secret key, so it must be protected.
-
Comparatively speaking, the overall structure of a complete JWT token information is as follows:
header (base64)+payload (base64)+Signature
Copy the code
3. Implementation of JWT
Code implementation:
Var token = jwt.sign({exp: = jwt.sign({exp: = jwt.sign({exp: = jwt.sign({exp: = jwt.sign)) Math.floor(Date.now() / 1000) + 60*60*24, name: data.person, .... }, config.secret,function(err, token) {
res.json({
msg: {
status: 1,
msg: "Login successful"}, data: { token: token, } }) }); JWT new Promise(function(resolve, reject) {
jwt.verify(token, config.secret, function(err, decoded) {
if (err) {
res.json({
ok: 0,
msg: err
})
} else{// If the validation is successful, do the corresponding background data processing}}); });Copy the code
Reference: JWT website