Json Web Token Knowledge
Learn reference blogs
Understand JWT usage scenarios and pros and cons
JWT use
Seriously, stop using JWT
1, the general situation of
It is a standard for the number of transfers between two entities in a Web environment. It’s really just a string. JWT is a standard name in a broad sense; JWT in its narrow sense refers to the token string that is passed. The basic use of JWT is a signature that determines whether a JWT (string) can be trusted so that a server can access its resources.
Of 2,
The data structure in the JWT string consists of three parts
- Header: Specifies the type and encryption algorithm. For example,
{
"alg":"HS256".// Algorithm name
"typ":"JWT" / / type
}
Copy the code
- Payload: Stores the message body, which stores basic information about the JWT. For example,
{
// User information, status, etc
"sub": "1234567890".// Holder id
"name": "John Doe".// The name of the holder
"admin": true. // Whether it is an administrator "expitation":1622709599 // Expiration timestamp
}
Copy the code
- Signature: The header and payload are encoded in Base64, and are encrypted using the encryption algorithm in the header. It is used for signature verification.
3. Validation process
The verification process is relatively simple. According to the definition in Signature, the content in header and payload is base64 encoded and the string encrypted using the encryption algorithm in header is compared with that in Signature. If not, the data in the JWT has been tampered with illegally.
Of course the client and server must use the same key to get the same encryption string. Another algorithm is also involved in the secure transmission of the key. See this article, Key Exchange Algorithms. Feel the magic of math.
4. Specific analysis
stateless
Since the JWT is stored on the client side, the server does not store the user’s state — that is, the JWT is stateless, and the server only needs to know the corresponding key to validate the JWT string passed by the client.
False cancellation
Different from the traditional cookie-session mode, when the user logs out, the server cannot do anything (because it does not save the user’s information). If the client is used to clear the stored corresponding JWT information, it is actually a fake log out behavior.
In fact, the problem described in 2 can be considered to implement one-to-one key mapping according to users. In this way, when a user logs out, the server can directly delete the key corresponding to the user to realize real logout.
Maintenance of expiration time
If you want to extend the expiration time of a session, you can extend it directly. However, JWT needs to change the information in the payload, which requires recalculation of the signature, causing performance problems.