Invalidate JWT Token in NodeJS

12,263

The general benefit of a JWT token authentication is that the tokens can contain all the session information you would normally keep in your session store. This saves considerable resources, especially in request-to-response times, because you do not have to look up session data on each and every request - the client gives you all that.

However, it comes at the cost of not being able to revoke a JWT token at a time of your choosing, because you lost track of state.

The obvious solution of keeping a list of invalidated tokens somewhere in your database kind of removes the above-described benefit because you again have to consult the database on every request.

A better option would be to issue short-lived JWT tokens, i.e. tokens valid only one minute. For a web application, an average user may perform several requests in a minute (a user navigating around your app). You can give each user a JWT token that will last a minute and when a request with expired token arrives, you simply issue them a new one.

Update: Issuing a new access token after presenting an expired token is a very bad idea - you should treat an expired token as invalid, as if it has been forged. Better approach is to have the client present a refresh token which will prove the user's identity, and only then issue new access token. Note that verifying a refresh token must be a stateful operation, ie. you must have a list of all valid refresh tokens per user somewhere in your database, because if the refresh token is compromised, the user must have a means of invalidating that token.

Share:
12,263
Kousha
Author by

Kousha

Biomedical Engineering Master student at UBC. I develop apps for both fun and large scale application for clients.

Updated on June 12, 2022

Comments

  • Kousha
    Kousha almost 2 years

    I followed this tutorial for using JWT token. The token expiry is set to only 5 minutes, but what if I wanted to invalidate the token after 1 minute of use? I want to be able to make an API call to /api/logout and that should delete my token.

    I'm using Express and Node.

    It seems like from what I could gather to do my option is to have a token db that stores the token. When I want to expire my token, I then expire/remove the token from the DB.

    I've also seen people casually say "remove" the token from the physical hard space, but I cannot figure out where the token is physically stored for me to remove it.