Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Reading several tutorials about using JWT for login/logout purposes in website/app, they all seem to suggest this mechanism of storing some user info (such as id, name, etc.) on the payload data, like (from official website):

{
  "id": 4,
  "name": "John Doe",
  "admin": true
}

and then storing the token somewhere in the frontend and include it for every request (e.g., in the Authorization header after Bearer). But then this form of keeping track of the logged-in user can lead to a serious race condition for operations that change the payload data like login and logout. Here is a simple senario: Assume user with id 4 is already logged in and the token containing the user id payload is already stored in the frontend. Now the front app sends some requests and the following actions take place in chronological order:

Action JWT token stored in the frontend login status
Front end sends request A asking for some arbitrary action {id:4} logged in
Front end sends request B asking to logout {id:4} logged in
The response of request B comes, carrying token with payload {} which means user is logged out {} logged out
The response of request A comes carrying token with payload {id:4} (same as its corresponding request) {id:4} logged in!!!!!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
387 views
Welcome To Ask or Share your Answers For Others

1 Answer

JWT token is generated and returned only on the response of the login request. On rest of the (action) calls, the JWT token is only sent to the backend, there is no new token received and updates at the client end. On logout, the token on the client end is cleared.

The race condition occurs only if between the login and logout requests then.

Ideally you cannot delete a JWT token since we do not store it on backend. Deletion is truly only when it expires. So a modified version of this model will maintain a list of all the logged out unexpired tokens in the backend for improved security. This can also help in avoiding the said race condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...