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!!!!! |