Invalidating JSON Web Tokens

For a new node.js project I'm working on, I'm thinking about switching over from a cookie based session approach (by this, I mean, storing an id to a key-value store containing user sessions in a user's browser) to a token-based session approach (no key-value store) using JSON Web Tokens (jwt).

The project is a game that utilizes - having a token-based session would be useful in such a scenario where there will be multiple communication channels in a single session (web and

How would one provide token/session invalidation from the server using the jwt Approach?

I also wanted to understand what common (or uncommon) pitfalls/attacks I should look out for with this sort of paradigm. For example, if this paradigm is vulnerable to the same/different kinds of attacks as the session store/cookie-based approach.

So, say I have the following (adapted from this and this):

Session Store Login:

app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        // Create session token
        var token= createSessionToken();

        // Add to a key-value database
        KeyValueStore.add({token: {userid:, expiresInMinutes: 60}});

        // The client should save this session token in a cookie
        response.json({sessionToken: token});

Token-Based Login:

var jwt = require('jsonwebtoken');
app.get('/login', function(request, response) {
    var user = {username: request.body.username, password: request.body.password };
    // Validate somehow
    validate(user, function(isValid, profile) {
        var token = jwt.sign(profile, 'My Super Secret', {expiresInMinutes: 60});
        response.json({token: token});


A logout (or invalidate) for the Session Store approach would require an update to the KeyValueStore database with the specified token.

It seems like such a mechanism would not exist in the token-based approach since the token itself would contain the info that would normally exist in the key-value store.



I too have been researching this question, and while none of the ideas below are complete solutions, they might help others rule out ideas, or provide further ones.

1) Simply remove the token from the client

Obviously this does nothing for server side security, but it does stop an attacker by removing the token from existence (ie. they would have to have stolen the token prior to logout).

2) Create a token blacklist

You could store the invalid tokens until their initial expiry date, and compare them against incoming requests. This seems to negate the reason for going fully token based in the first place though, as you would need to touch the database for every request. The storage size would likely be lower though, as you would only need to store tokens that were between logout & expiry time (this is a gut feeling, and is definitely dependent on context).

3) Just keep token expiry times short and rotate them often

If you keep the token expiry times at short enough intervals, and have the running client keep track and request updates when necessary, number 1 would effectively work as a complete logout system. The problem with this method, is that it makes it impossible to keep the user logged in between closes of the client code (depending on how long you make the expiry interval).

Contingency Plans

If there ever was an emergency, or a user token was compromised, one thing you could do is allow the user to change an underlying user lookup ID with their login credentials. This would render all associated tokens invalid, as the associated user would no longer be able to be found.

I also wanted to note that it is a good idea to include the last login date with the token, so that you are able to enforce a relogin after some distant period of time.

In terms of similarities/differences with regards to attacks using tokens, this post addresses the question:


The ideas posted above are good, but a very simple and easy way to invalidate all the existing JWTs is simply to change the secret.

If your server creates the JWT, signs it with a secret (JWS) then sends it to the client, simply changing the secret will invalidating all existing tokens and require all users to gain a new token to authenticate as their old token suddenly becomes invalid according to the server.

It doesn't require any modifications to the actual token contents (or lookup ID).

Clearly this only works for an emergency case when you wanted all existing tokens to expire, for per token expiry one of the solutions above is required (such as short token expiry time or invalidating a stored key inside the token).


This is primarily a long comment supporting and building on the answer by @mattway


Some of the other proposed solutions on this page advocate hitting the datastore on every request. If you hit the main datastore to validate every authentication request, then I see less reason to use JWT instead of other established token authentication mechanisms. You've essentially made JWT stateful, instead of stateless if you go to the datastore each time.

(If your site receives a high volume of unauthorized requests, then JWT would deny them without hitting the datastore, which is helpful. There are probably other use cases like that.)


Truly stateless JWT authentication cannot be achieved for a typical, real world web app because stateless JWT does not have a way to provide immediate and secure support for the following important use cases:

User's account is deleted/blocked/suspended.

User's password is changed.

User's roles or permissions are changed.

User is logged out by admin.

Any other application critical data in the JWT token is changed by the site admin.

You cannot wait for token expiration in these cases. The token invalidation must occur immediately. Also, you cannot trust the client not to keep and use a copy of the old token, whether with malicious intent or not.

Therefore: I think the answer from @matt-way, #2 TokenBlackList, would be most efficient way to add the required state to JWT based authentication.

You have a blacklist that holds these tokens until their expiration date is hit. The list of tokens will be quite small compared to the total number of users, since it only has to keep blacklisted tokens until their expiration. I'd implement by putting invalidated tokens in redis, memcached or another in-memory datastore that supports setting an expiration time on a key.

You still have to make a call to your in-memory db for every authentication request that passes initial JWT auth, but you don't have to store keys for your entire set of users in there. (Which may or may not be a big deal for a given site.)


I would keep a record of the jwt version number on the user model. New jwt tokens would set their version to this.

When you validate the jwt, simply check that it has a version number equal to the users current jwt version.

Any time you want to invalidate old jwts, just bump the users jwt version number.


Haven't tried this yet, and it is uses a lot of information based on some of the other answers. The complexity here is to avoid a server side data store call per request for user information. Most of the other solutions require a db lookup per request to a user session store. That is fine in certain scenarios but this was created in an attempt to avoid such calls and make whatever required server side state to be very small. You will end up recreating a server side session, however small to provide all the force invalidation features. But if you want to do it here is the gist:


  • Mitigate use of a data store (state-less).
  • Ability to force log out all users.
  • Ability to force log out any individual at any time.
  • Ability to require password re-entry after a certain amount of time.
  • Ability to work with multiple clients.
  • Ability to force a re-log in when a user clicks logout from a particular client. (To prevent someone "un-deleting" a client token after user walks away - see comments for additional information)

The Solution:

  • Use short lived (<5m) access tokens paired with a longer lived (few hours) client stored refresh-token.
  • Every request checks either the auth or refresh token expiration date for validity.
  • When the access token expires, the client uses the refresh token to refresh the access token.
  • During the refresh token check, the server checks a small blacklist of user ids - if found reject the refresh request.
  • When a client doesn't have a valid(not expired) refresh or auth token the user must log back in, as all other requests will be rejected.
  • On login request, check user data store for ban.
  • On logout - add that user to the session blacklist so they have to log back in. You would have to store additional information to not log them out of all devices in a multi device environment but it could be done by adding a device field to the user blacklist.
  • To force re-entry after x amount of time - maintain last login date in the auth token, and check it per request.
  • To force log out all users - reset token hash key.

This requires you to maintain a blacklist(state) on the server, assuming the user table contains banned user information. The invalid sessions blacklist - is a list of user ids. This blacklist is only checked during a refresh token request. Entries are required to live on it as long as the refresh token TTL. Once the refresh token expires the user would be required to log back in.


  • Still required to do a data store lookup on the refresh token request.
  • Invalid tokens may continue to operate for access token's TTL.


  • Provides desired functionality.
  • Refresh token action is hidden from the user under normal operation.
  • Only required to do a data store lookup on refresh requests instead of every request. ie 1 every 15 min instead of 1 per second.
  • Minimizes server side state to a very small blacklist.

With this solution an in memory data store like reddis isn't needed, at least not for user information as you are as the server is only making a db call every 15 or so minutes. If using reddis, storing a valid/invalid session list in there would be a very fast and simpler solution. No need for a refresh token. Each auth token would have a session id and device id, they could be stored in a reddis table on creation and invalidated when appropriate. Then they would be checked on every request and rejected when invalid.


An approach I've been considering is to always have an iat (issued at) value in the JWT. Then when a user logs out, store that timestamp on the user record. When validating the JWT just compare the iat to the last logged out timestamp. If the iat is older, then it's not valid. Yes, you have to go to the DB, but I'll always be pulling the user record anyway if the JWT is otherwise valid.

The major downside I see to this is that it'd log them out of all their sessions if they're in multiple browsers, or have a mobile client too.

This could also be a nice mechanism for invalidating all JWTs in a system. Part of the check could be against a global timestamp of the last valid iat time.


I'm a bit late here, but I think I have a decent solution.

I have a "last_password_change" column in my database that stores the date and time when the password was last changed. I also store the date/time of issue in the JWT. When validating a token, I check if the password has been changed after the token was issued and if it was the token is rejected even though it hasn't expired yet.


You can have a "last_key_used" field on your DB on your user's document/record.

When the user logs in with user and pass, generate a new random string, store it in the last_key_used field, and add it to the payload when signing the token.

When the user logs in using the token, check the last_key_used in the DB to match the one in the token.

Then, when user does a logout for instance, or if you want to invalidate the token, simply change that "last_key_used" field to another random value and any subsequent checks will fail, hence forcing the user to log in with user and pass again.


------------------------Bit late for this answer but may be it will help to someone------------------------

From the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token. You may use different methods with respect to JWT which are mentioned above. But here i go with the jwt-redis.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
            // your code
            // error handling

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -


Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

May be this will help to someone


Why not just use the jti claim (nonce) and store that in a list as a user record field (db dependant, but at very least a comma-separated list is fine)? No need for separate lookup, as others have pointed out presumably you want to get the user record anyway, and this way you can have multiple valid tokens for different client instances ("logout everywhere" can reset the list to empty)

  1. Give 1 day expiry time for the tokens
  2. Maintain a daily blacklist.
  3. Put the invalidated / logout tokens into the blacklist

For token validation, check for the token expiry time first and then the blacklist if token not expired.

For long session needs, there should be a mechanism for extending token expiry time.


Late to the party, MY two cents are given below after some research. During logout, make sure following things are happening...

Clear the client storage/session

Update the user table last login date-time and logout date-time whenever login or logout happens respectively. So login date time always should be greater than logout (Or keep logout date null if the current status is login and not yet logged out)

This is way far simple than keeping additional table of blacklist and purging regularly. Multiple device support requires additional table to keep loggedIn, logout dates with some additional details like OS-or client details.


Keep an in-memory list like this

user_id   revoke_tokens_issued_before
123       2018-07-02T15:55:33
567       2018-07-01T12:34:21

If your tokens expire in one week then clean or ignore the records older than that. Also keep only the most recent record of each user. The size of the list will depend on how long you keep your tokens and how often users revoke their tokens. Use db only when the table changes. Load the table in memory when your application starts.


Unique per user string, and global string hashed together

to serve as the JWT secret portion allow both individual and global token invalidation. Maximum flexibility at the cost of a db lookup/read during request auth. Also easy to cache as well, since they are seldom changing.


I did it the following way:

  1. Generate a unique hash, and then store it in redis and your JWT. This can be called a session
    • We'll also store the number of requests the particular JWT has made - Each time a jwt is sent to the server, we increment the requests integer. (this is optional)

So when a user logs in, a unique hash is created, stored in redis and injected into your JWT.

When a user tries to visit a protected endpoint, you'll grab the unique session hash from your JWT, query redis and see if it's a match!

We can extend from this and make our JWT even more secure, here's how:

Every X requests a particular JWT has made, we generate a new unique session, store it in our JWT, and then blacklist the previous one.

This means that the JWT is constantly changing and stops stale JWT's being hacked, stolen, or something else.


If you want to be able to revoke user tokens, you can keep track of all issued tokens on your DB and check if they're valid (exist) on a session-like table. The downside is that you'll hit the DB on every request.

I haven't tried it, but i suggest the following method to allow token revocation while keeping DB hits to a minimum -

To lower the database checks rate, divide all issued JWT tokens into X groups according to some deterministic association (e.g., 10 groups by first digit of the user id).

Each JWT token will hold the group id and a timestamp created upon token creation. e.g., { "group_id": 1, "timestamp": 1551861473716 }

The server will hold all group ids in memory and each group will have a timestamp that indicates when was the last log-out event of a user belonging to that group. e.g., { "group1": 1551861473714, "group2": 1551861487293, ... }

Requests with a JWT token that have an older group timestamp, will be checked for validity (DB hit) and if valid, a new JWT token with a fresh timestamp will be issued for client's future use. If the token's group timestamp is newer, we trust the JWT (No DB hit).

So -

  1. We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out.
  2. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone)
  3. We limit the number of groups to limit the amount of timestamps held in memory
  4. Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

If "logout from all devices" option is acceptable (in most cases it is):

  • Add the token version field to the user record.
  • Add the value in this field to the claims stored in the JWT.
  • Increment the version every time the user logs out.
  • When validating the token compare its version claim to the version stored in the user record and reject if it is not the same.

A db trip to get the user record in most cases is required anyway so this does not add much overhead to the validation process. Unlike maintaining a blacklist, where DB load is significant due to the necessity to use a join or a separate call, clean old records and so on.


This seems really difficult to solve without a DB lookup upon every token verification. The alternative I can think of is keeping a blacklist of invalidated tokens server-side; which should be updated on a database whenever a change happens to persist the changes across restarts, by making the server check the database upon restart to load the current blacklist.

But if you keep it in the server memory (a global variable of sorts) then it's not gonna be scalable across multiple servers if you are using more than one, so in that case you can keep it on a shared Redis cache, which should be set-up to persist the data somewhere (database? filesystem?) in case it has to be restarted, and every time a new server is spun up it has to subscribe to the Redis cache.

Alternative to a black-list, using the same solution, you can do it with a hash saved in redis per session as this other answer points out (not sure that would be more efficient with many users logging in though).

Does it sound awfully complicated? it does to me!

Disclaimer: I have not used Redis.


If you are using axios or a similar promise-based http request lib you can simply destroy token on the front-end inside the .then() part. It will be launched in the response .then() part after user executes this function (result code from the server endpoint must be ok, 200). After user clicks this route while searching for data, if database field user_enabled is false it will trigger destroying token and user will immediately be logged-off and stopped from accessing protected routes/pages. We don't have to await for token to expire while user is permanently logged on.

function searchForData() {   // front-end js function, user searches for the data
    // protected route, token that is sent along http request for verification
    var validToken = 'Bearer ' + whereYouStoredToken; // token stored in the browser 

    // route will trigger destroying token when user clicks and executes this func'/my-data', {headers: {'Authorization': validToken}})
     .then((response) => {
   // If Admin set user_enabled in the db as false, we destroy token in the browser localStorage
       if ( === false) {  // user_enabled is field in the db
           window.localStorage.clear();  // we destroy token and other credentials
     .catch((e) => {

I just save token to users table, when user login I will update new token, and when auth equal to the user current jwt.

I think this is not the best solution but that work for me.


I am going to answer If we need to provide logout from all devices feature when we are using JWT. This approach will use database look-ups for each requests. Because we need a persistence security state even if there is a server crash. In the user table we will have two columns

  1. LastValidTime (default: creation time)
  2. Logged-In (default: true)

Whenever there is a log out request from the user we will update the LastValidTime to current time and Logged-In to false. If there is a log in request we wont change LastValidTime but Logged-In will be set to true.

When we create the JWT we will have the JWT creation time in the payload. When we authorize for a service we will check 3 conditions

  1. Is JWT valid
  2. Is JWT payload creation time is greater than User LastValidTime
  3. Is user Logged-In

Lets see a practical scenario.

User X has two devices A, B. He logged in to our server at 7 pm using device A and device B. (lets say JWT expire time is 12 hrs). A and B both have JWT with createdTime : 7pm

At 9 pm he lost his device B. He immediately log out from the device A. That means Now our database X user entry has LastValidTime as "ThatDate:9:00:xx:xxx" and Logged-In as "false".

At 9:30 the Mr.Thief tries to log in using device B. We will check the database even the Logged-In is false so we wont allow.

At 10 pm Mr.X log in from his device A. Now device A has JWT with created time : 10pm. Now database Logged-In is set to "true"

At 10:30 pm Mr.Thief tries to log in. Even though the Logged-In is true. The LastValidTime is 9 pm in the database but B's JWT has created time as 7pm. So he wont be allowed to access the service. So using device B without having the password he cannot use already created JWT after one device log out.


The following approach could give best of both worlds solution:

Let "immediate" mean "~1 minute".


  1. User attempts a successful login:

    A. Add an "issue time" field to the token, and keep the expiry time as needed.

    B. Store the hash of user's password's hash or create a new field say tokenhash in the user's table. Store the tokenhash in the generated token.

  2. User accesses a url:

    A. If the "issue time" is in the "immediate" range, process the token normally. Don't change the "issue time". Depending upon the duration of "immediate" this is the duration one is vulnerable in. But a short duration like a minute or two shouldn't be too risky. (This is a balance between performance and security). Three is no need to hit the db here.

    B. If the token is not in the "immediate" range, check the tokenhash against the db. If its okay, update the "issue time" field. If not okay then don't process the request (Security is finally enforced).

  3. User changes the tokenhash to secure the account. In the "immediate" future the account is secured.

We save the database lookups in the "immediate" range. This is most beneficial if there are a bursts of requests from the client in the "immediate" time duration.


Kafka message queue and local black lists

I thought about using a messaging system like kafka. Let me explain:

You could have one micro service (let call it userMgmtMs service) for example which is responsible for the login and logout and to produce the JWT token. This token then gets passed to the client.

Now the client can use this token to call different micro services (lets call it pricesMs), within pricesMs there will be NO database check to the users table from which the initial token creation was triggered. This database has only to exist in userMgmtMs. Also the JWT token should include the permissions / roles so that the pricesMs do not need to lookup anything from the DB to allow spring security to work.

Instead of going to the DB in the pricesMs the JwtRequestFilter could provide a UserDetails object created by the data provided in the JWT token (without the password obviously).

So, how to logout or invalidate a token? Since we do not wanna call the database of userMgmtMs with every request for priecesMs (which would introduce quite a lot of unwanted dependencies) a solution could be to use this token blacklist.

Instead of keeping this blacklist central and haveing a dependency on one table from all microservices, I propose to use a kafka message queue.

The userMgmtMs is still responsible for the logout and once this is done it puts it into its own blacklist (a table NOT shared among microservices). In addition it sends a kafka event with the content of this token to a internal kafka service where all other microservices are subscribed to.

Once the other microservices receive the kafka event they will put it as well in their internal blacklist.

Even if some microservices are down at the time of logout they will eventually go up again and will receive the message at a later state.

Since kafka is developed so that clients have their own reference which messages they did read it is ensured that no client, down or up will miss any of this invalid tokens.

The only issue again what I can think of is that the kafka messaging service will again introduce a single point of failure. But it is kind of reversed because if we have one global table where all invalid JWT tokens are saved and this db or micro service is down nothing works. With the kafka approach + client side deletion of JWT tokens for a normal user logout a downtime of kafka would in most cases not even be noticeable. Since the black lists are distributed among all microservies as an internal copy.

In the off case that you need to invalidate a user which was hacked and kafka is down this is where the problems start. In this case changing the secret as a last resort could help. Or just make sure kafka is up before doing so.

Disclaimer: I did not implement this solution yet but somehow I feel that most of the proposed solution negate the idea of the JWT tokens with having a central database lookup. So I was thinking about another solution.

Please let me know what you think, does it make sense or is there an obvious reason why it cant?


IAM solution like Keycloak (which I'have worked on) provide Token Revocation endpoint like

Token Revocation Endpoint /realms/{realm-name}/protocol/openid-connect/revoke

Of if you simply want to logout an useragent(or user), you could call an endpoint as well(this would simply invalidate the Tokens). Again, in the case of Keycloak, the Relying Party just needs to call the endpoint


Link in case if you want to learn more


you can signout with jwt tokens by adding it with a cookie first you need to install cookie-parser by doing npm i cookie-parser

and import it as const cookieParser = require('cookie-parser'); and use it as app.use(cookieParser()); in app.js

now you need to add the token to signin and login


//generate a signed token
  let token;
    const error = new HttpError(
      'creating user failed,please try again',500
    return next(error);
  //persist the token as 't' in cookie with expiry date
  res.cookie('t',token,{expire : new Date() + 9999})
  //return response with user and token to frontend 
      userId: newUser._id,,

so here I generated a token with using jwt.sing() and then I store the token as t in cookie with expiry date and return the response with user details and token to frontend.

so now comes the MAIN PART to singout create a signout route and use as

const signout = (req,res,next) => {
  res.json({message:'Signout Success'});


you can put a comment if you have any doubts.


An alternative would be to have a middleware script just for critical API endpoints.
This middleware script would check in the database if the token is invalidated by an admin.
This solution may be useful for cases where is not necessary to completely block the access of a user right away.


In this example, I am assuming the end user also has an account. If this isn't he case, then the rest of the approach is unlikely to work.

When you create the JWT, persist it in the database, associated with the account that is logging in. This does mean that just from the JWT you could pull out additional information about the user, so depending on the environment, this may or may not be OK.

On every request after, not only do you perform the standard validation that (I hope) comes with what ever framework you use (that validates the JWT is valid), it also includes soemthing like the user ID or another token (that needs to match that in the database).

When you log out, delete the cookie (if using) and invalidate the JWT (string) from the database. If the cookie can't be deleted from the client side, then at least the log out process will ensure the token is destroyed.

I found this approach, coupled with another unique identifier (so there are 2 persist items in the database and are available to the front end) with the session to be very resilient


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.