当前位置:网站首页>JWT implementation

JWT implementation

2022-06-23 22:08:00 Great inventor

What should we do if we have to force users to log out ?

Similar can be used oauth2.0 Practices in the agreement , Issued after certification 2 individual token,access token and refresh token.

  • access token The access token is a JWT, Set a shorter expiration time , such as 1 Hours . Each time the access token calls the back-end service, it needs to carry , The frequency of going back and forth to the network is very high , The more likely it is to be exposed , Setting a shorter expiration time can also reduce security risks .
  • refresh token Refresh token , It's OK not to JWT, Set a longer expiration time , such as 1 Months . Refresh token is mainly used to exchange for new access token. Because it is only passed to the server when the access token is about to expire or has expired , Longer expiration times do not pose much security risk . Issued by token When , Save the refresh token only in redis And set expiration time . When a refresh token is used in exchange for a new access token , You need to determine redis Whether the refresh token exists in the , If it doesn't exist , The refresh fails , Users need to log in again .

The client needs to maintain the login status for a long time , When the access token fails , Automatically use the refresh token to obtain a new access token . Or before the access token expires , Refresh the token in advance .

Now we want to kick people , You only need to change the refresh token associated with the user from redis In the delete . After the current access token expires , Naturally, there is no way to refresh the token . So as to achieve the purpose of forcing users to log out .

One drawback of this design is that forcing users to log out is not timely . There needs to be a time to wait for the access token to expire . If you want high timeliness , You can set the expiration time of the access token to be shorter , But refresh token The frequency of . This needs to be weighed against your own business .

Every time the service is called api It is still original jwt Stateless Authentication , No need to access any central storage . Access to the central storage is required only when the access token is refreshed . It is also a compromise .

原网站

版权声明
本文为[Great inventor]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112181254360219.html