Revoking JWTs & JWT Expiration (2024)

I have been talking with developers about JSON Web Tokens (JWTs) recently and one question keeps coming up: “How do I revoke a JWT?”

If you poke around online, you’ll find that the most common answers are:

  • Set the duration of the JWT to a short period (a few minutes or seconds)
  • Implement complicated blacklisting techniques
  • Store every JWT so you can validate them

There is not a simple solution because JWTs are designed to be portable, decoupled identities. Once you authenticate against an identity provider (IdP) and get back a JWT, you don’t need to ask the IdP if the JWT is valid. This is particularly powerful when you use RSA public/private key signing. The IdP signs the JWT using the private key and then any service that has the public key can verify the integrity of the JWT.

Here’s a diagram that illustrates this architecture:

Revoking JWTs & JWT Expiration (1)

The ToDo Backend in the diagram can use the JWT and the public key to verify the JWT and then pull the user’s Id (in this case the subject) out of the JWT. The ToDo Backend can then use the user’s Id to perform operations on that user’s data. However, because the ToDo Backend isn’t verifying the JWT with the IdP, it has no idea if an administrator has logged into the IdP and locked or deleted that user’s account.

Reduce the duration of the JWT

The most common solution is to reduce the duration of the JWT and revoke the refresh token so that the user can’t generate a new JWT. With this setup, the JWT’s expiration duration is set to something short (5-10 minutes) and the refresh token is set to something long (2 weeks or 2 months). At any time, an administrator can revoke the refresh token which means that the user must re-authenticate to get a new JWT. That is unless they happen to have a valid JWT.

Here’s where things get tricky. That user basically has 5 to 10 minutes to use the JWT before it expires. Once it expires, they’ll use their current refresh token to try and get a new JWT. Since the refresh token has been revoked, this operation will fail and they’ll be forced to login again.

It’s this 5 to 10 minute window that freaks everyone out. So, how do we fix it?

Webhooks

One way is leveraging a distributed event system that notifies services when refresh tokens have been revoked. The IdP broadcasts an event when a refresh token is revoked and other backends/services listen for the event. When an event is received the backends/services update a local cache that maintains a set of users whose refresh tokens have been revoked. This cache is checked whenever a JWT is verified to determine if the JWT should be revoked or not. This is all based on the duration of JWTs and expiration instant of individual JWTs.

Example: Revoking JWTs in FusionAuth

To illustrate this, I’m going to use FusionAuth’s event and Webhook system as well as the jwt.refresh-token.revoke event. If you are building your own IdP or using another system, you might need to build out your own eventing system based on this article.

The FusionAuth jwt.refresh-token.revoke event looks like this:

{ "event": { "type": "jwt.refresh-token.revoke", "applicationTimeToLiveInSeconds": { "cc0567da-68a1-45f3-b15b-5a6228bb7146": 600 }, "userId": "00000000-0000-0000-0000-000000000001" }}

Next, let’s write a simple Webhook in our application that will receive this event and update the JWTManager. (NOTE: our example has a variable called applicationId that is a global variable that stores the Id of the application itself - in this case it would be cc0567da-68a1-45f3-b15b-5a6228bb7146). Our code below is written in Node.js and uses the FusionAuth Node client library.

/* Handle FusionAuth event. */router.post('/fusionauth-webhook', function(req, res, next) { JWTManager.revoke(req.body.event.userId, req.body.event.applicationTimeToLiveInSeconds[applicationId]); res.sendStatus(200);});

Here is how the JWTManager maintains the list of user Ids whose JWTs should be revoked. Our implementation also starts a thread to clean up after itself so we don’t run out of memory.

const JWTManager = { revokedJWTs: {}, /** * Checks if a JWT is valid. This assumes that the JWT contains a property named <code>exp</code> that is a * NumericDate value defined in the JWT specification and a property named <code>sub</code> that is the user Id the * JWT belongs to. * * @param {object} jwt The JWT object. * @returns {boolean} True if the JWT is valid, false if it isn't. */ isValid: function(jwt) { const expiration = JWTManager.revokedJWTs[jwt.sub]; return expiration === undefined || expiration === null || expiration < jwt.exp * 1000; }, /** * Revokes all JWTs for the user with the given Id using the duration (in seconds). * * @param {string} userId The user Id (usually a UUID as a string). * @param {Number} durationSeconds The duration of all JWTs in seconds. */ revoke: function(userId, durationSeconds) { JWTManager.revokedJWTs[userId] = Date.now() + (durationSeconds * 1000); }, /** * Cleans up the cache to remove old user's that have expired. * @private */ _cleanUp: function() { const now = Date.now(); Object.keys(JWTManager.revokedJWTs).forEach((item, index, _array) => { const expiration = JWTManager.revokedJWTs[item]; if (expiration < now) { delete JWTManager.revokedJWTs[item]; } }); }};/** * Set an interval to clean-up the cache. */setInterval(JWTManager._cleanUp, 7000);

Our backend also needs to ensure that it checks JWTs with the JWTManager on each API call.

router.get('/todo', function(req, res, next) { const jwt = _parseJWT(req); if (!JWTManager.isValid(jwt)) { res.sendStatus(401); return; } // ...});

And finally we configure our Webhook in FusionAuth:

Revoking JWTs & JWT Expiration (2)

We can now revoke a user’s refresh token and FusionAuth will broadcast the event to our Webhook. The Webhook then updates the JWTManager which will cause JWTs for that user to be revoked.

This solution works well even in large systems with numerous backends. It requires the use of refresh tokens and an API that allows refresh tokens to be revoked. The only caveat is to be sure that your JWTManager code cleans up after itself to avoid running out memory.

If you are using FusionAuth, you can use the Webhook and Event system to build this feature into your application quickly. We are also writing JWTManager implementations into each of our client libraries so you don’t have to write those yourself. At the time of this writing, the Java and Node clients both have a JWTManager you can use. The other languages might have a JWTManager implementation now but if they don’t, just submit a support ticket or a GitHub issue and we will write one for you.

Revoking JWTs & JWT Expiration (2024)

FAQs

Revoking JWTs & JWT Expiration? ›

The most common solution is to reduce the duration of the JWT and revoke the refresh token so that the user can't generate a new JWT. With this setup, the JWT's expiration duration is set to something short (5-10 minutes) and the refresh token is set to something long (2 weeks or 2 months).

How to fix JWT expired error? ›

Check the 'Expiration Time' setting in the JWT profile. If it's set to a short duration, consider increasing it. Ensure that the system time on your server is correct. If the system time is ahead of the actual time, it could cause tokens to expire prematurely.

Can I revoke a JWT token? ›

Token blacklisting is a widely used method to revoke JWT tokens. This approach involves maintaining a server-side blacklist containing identifiers, such as the jti claim or a user ID, of tokens that should be considered invalid.

How to deal with JWT expiration? ›

For Web Apps: If you set the expiration time to 1 week, do not use the token for 1 week. Use it less than a week and get a new token before the old token expires. For example, make the browser send out a request to exchange for a new token at the sixth day.

What does "jwt is expired" mean? ›

JWTs (JSON Web Tokens) are a compact, URL-safe means of representing claims to be transferred between two parties. However, once a JWT expires, it should no longer be considered valid, and relying on an expired JWT can lead to security vulnerabilities.

How do I refresh my JWT token before expiration? ›

To refresh the token, your API needs a new endpoint that receives a valid, not expired JWT and returns the same signed JWT with the new expiration field. Then the web application will store the token somewhere.

How do I fix an expired token? ›

Once expired, you need to re-authenticate to obtain a new token. Doing this prevents the same token from being used for an extended period of time, thereby reducing the risk of misappropriation. You can also use refresh tokens to renew new access tokens.

What happens when you revoke a token? ›

The invalidation takes place immediately, and the token cannot be used again after the revocation. Each revocation request invalidates all the tokens that have been issued for the same authorization grant.

How to check expiry of JWT token? ›

To determine the expiration time of the current JWT token that was created for your Azure AD connector app, you can decode the token and check the value of the “exp” claim. There are various online JWT decoding tools available that you can use to decode the token, such as jwt.io or jwt-decode.com.

What is the default expiration of JWT? ›

After this time, the JWT is no longer valid. At maximum, the expiration period can be set up to 24 hours from time of issue. Note: This is an expiration time for the JWT token and not the access token. Access token expiration is set to 24 hours by default.

What is the best practice for JWT access token expiration? ›

Access token expiration: Access tokens should have a short expiration time, typically between 15 minutes to 1 hour. This is because access tokens are used to access protected routes and should be short-lived to minimize damage in case of token theft.

Can JWTs be revoked? ›

Reduce the duration of the JWT

At any time, an administrator can revoke the refresh token which means that the user must re-authenticate to get a new JWT. That is unless they happen to have a valid JWT.

Is JWT bad for authentication? ›

JWT token is not encrypted, it's just base64UrlEncoded. So, don't put any sensitive information in payload. Meaning, if for some reason an access token is stolen, an attacker will be able to decode it and see information in payload.

How to fix JWT expired error in postman? ›

After some time (TTL) it will expire and you'll get message like that. Then you have to repeat authentication to get new token. So just repeat request you made at start, pass again credentials, collect and store again new token and keep using it as before.

How to fix JWT expired error yahoo? ›

If you see the JWT expired error below, then ensure the JWT claim values exp and iat are correct. Both values should be in seconds (EPOCH time) and exp should be in the future, but it should be less than sthe erver side configured time (i.e., 24 hours).

Top Articles
Why do I owe a penalty and interest and what can I do about it?
How to activate sms on android
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6468

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.