JWT explanation and token expiration automatic renewal solution

JWT explanation and token expiration automatic renewal solution

1.What is token

Token is a string of strings generated by the server as a token for client requests. When logging in for the first time, the server generates a Token and returns this Token to the client. In the future, the client only needs to bring this token. Token can come to request data without having to bring user name and password again. In fact, token can be called a secret code more informally. Before some data is transmitted, the secret code must be checked first. Different secret codes are authorized for different data operations.

Benefits of using tokens:
Token-based authentication is stateless, and we do not store user information in the server or Session.

2.What is JWT

Json web token (JWT) is an open standard based on JSON for transmitting claims between web application environments. The token is designed to be compact and secure, especially suitable for single sign-on (SSO) on distributed sites. Scenes. JWT claims are generally used to transfer authenticated user identity information between identity providers and service providers in order to obtain resources from the resource server. Some additional claim information necessary for other business logic can also be added. The token is also It can be used directly for authentication or encrypted.

JWT is composed of three pieces of data:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E 2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
is analyzed as follows:
Insert image description here
We call the first part head (header), and the second part we call load
visa (signature). (payload, similar to items carried on an airplane), the third part is

3.Token expiration automatic renewal plan

3.1 Token expiration

The token expiration time generated in our backend can be set. For example, if the expiration is set to 30 minutes, it means that you need to log in again after 30 minutes.

3.2 Solution

Option 1: Regenerate a new token for every request [too high frequency, poor performance]

Option 2: Each time you log in, two tokens are generated and returned to the front end. One is the token used to identify the user, and the other token is used to refresh the token.

Option 3: After logging in, return the token to the front end and set the expiration time for 30 minutes. The front end stores the token in the request header for each request and sends the request. When the back end receives the request, it obtains the request header and performs jwt analysis to determine the expiration time. Is it less than 10 minutes? If it is less than 10 minutes, generate a new token and return it in responseHearde.

おすすめ

転載: blog.csdn.net/weixin_43249535/article/details/122393006