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.
A common approach for invalidating tokens when a user changes their password is to sign the token with a hash of their password. Thus if the password changes, any previous tokens automatically fail to verify.
A JWT can still be valid even after it has been deleted from the client, depending on the expiration date of the token. So, invalidating it makes sure it's not being used again for authentication purposes. If the lifetime of the token is short, it might not be an issue.
The most common way to revoke access to resources protected by a JWT involves setting its duration to a short period of time and revoking the refresh token so that the user can't generate a new token.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With