How to expire JWT token on logout? - Tutorialswebsite (2024)

How to expire JWT token on logout from the app or website?. It is an important question for node js programmers who are using the JWT library to generate an authentication token.

Table of Contents

JSON Web Tokens

JWT (JSON Web Tokens) provides a way to handle user authentication in a stateless way. What does that mean? Alright, It helps to manage authentication in any storage without storing the authentication state, whether it be a session or a database. Therefore you do not need to access the session or perform a database query while verifying the user’s authentication status. Instead, you create a token based on the user payload of your choice and use it to identify the user on the server in client-side requests.

So, basically, once a token is created, it can be used permanently, or until it is expired. After specified time, JWT generator can get an option to invalidate the token.

So what should you do if you wish to invalidate an existing token? What should you do when the user decides to sign out or let’s say change password?

Expire JWT token on logout

Okay, so normally the client side stores the token somewhere while using JWT authentication, and attaches it to any request that needs authentication. Thus, the first thing to do when logging out is simply delete the token that you saved on the client (i.e. local storage browser). In that case, the client does not have a token to put in the request, thus causing unauthorized status of response. But still does that be enough? Anyway, the specific client (browser, app) will no longer be authenticated, but the token still exists somewhere, and is still valid! If someone hascopied the token from the request he / she would still be able to make requests on the user’s behalf!.

Actually, JWT serves a different purpose than a session and it is not possible to forcefully delete or invalidate an existing token.

Can token expire?

Yeah, the tokens can be expired. but, you can’t do that on demand.

You can pass an expiry time when signing a user payload for a JWT. You need to provide it as a field called exp in the payload like below:

In the above example, the iat field here stands for “issued at”. This token is set to expire 5 seconds after it was issued. The expiration field takes number of milliseconds since the start of Unix epoch.

If you don’t want to have forever valid tokens, you should always set a reasonable expiration time on you JWT.

For a NodeJS app the code should look something like this:

2

3

4

5

6

7

8

9

10

11

12

13

const jwt = require('jsonwebtoken');

const payload = {

"userid": "1234567890",

"username": "Tutorials Website",

"iat": 1516234022,

"iat": 1516234022

}

const token = jwt.sign(payload, 'your-secret', {expiresIn: '1d'})

Here, We will go with one day tokens and generate them in our login action.

So, with this example, all users will be automatically logged out after 1 day of using your app.

Note: If you are using one of the JWT libraries, then most likely you can also pass an expiration time in the signing method options.

“Awesome, but I still want to log out!”

Well, As mentioned above, after a token has been generated, you can not manually expire. You can not log out on the server side with JWT.

How to expire JWT token on logout? - Tutorialswebsite (1)

If you want to restrict the usage of a token when a user logs out. simply follow these 4 bullet points:

  • Set a reasonable expiration time on tokens
  • Delete the stored token from client-side upon log out
  • Have DB of no longer active tokens that still have some time to live
  • Query provided token against The Blacklist on every authorized request

Also Read: Uploading file or image using multer in Node js

Conclusion

As you know, JWT is stateless, which means you can store everything you need in the payload and skip executing a DB query on every request. So if you’re trying to provide a strict log-out functionality, that can’t wait for the auto-expiration token, even though you’ve cleaned the token from the client-side, then you might need to ignore the stateless logic and do some queries.

Are you looking for website Designer and developer in delhi, India?

How to expire JWT token on logout? - Tutorialswebsite (2)

Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications likeDzone,e27.co

I am a seasoned expert in web development and Node.js programming, specializing in authentication mechanisms such as JSON Web Tokens (JWT). My in-depth knowledge and practical experience in this field make me well-equipped to address the topic at hand.

In the provided article, the author discusses the importance of expiring JWT tokens on logout from an app or website, particularly for Node.js programmers utilizing the JWT library for authentication. Let's break down the concepts used in the article:

1. JSON Web Tokens (JWT)

JWT is a standard for handling user authentication in a stateless manner. It allows the management of authentication without storing the state in a session or database. Instead, a token is created based on user payload and used for identification on the server in client-side requests.

2. Expire JWT Token on Logout

The article emphasizes the need to expire JWT tokens when a user logs out. The process involves deleting the token stored on the client side (e.g., in local storage), preventing the client from including the token in subsequent authentication requests.

3. Can Token Expire?

Yes, tokens can expire. The article explains that tokens are set to expire based on an expiry time provided during the token creation. The expiration time is specified in the payload using the "exp" field. The example provided sets the token to expire 5 seconds after issuance.

4. Setting Expiry Time in Node.js

For Node.js applications using the JWT library, the article suggests setting a reasonable expiration time for tokens. It provides sample code demonstrating how to sign a user payload with an expiration time, ensuring that users will be automatically logged out after a specified duration.

5. Log Out Considerations

The article acknowledges that JWT serves a different purpose than a session, and it's not possible to forcefully delete or invalidate an existing token. However, it recommends a series of steps to restrict token usage when a user logs out, including setting a reasonable expiration time, deleting the stored token on the client side, maintaining a database of inactive tokens, and checking against a blacklist on authorized requests.

6. Conclusion

The conclusion highlights the stateless nature of JWT, enabling the storage of necessary information in the payload without frequent database queries. It suggests that for strict logout functionality that can't wait for auto-expiration, developers may need to bypass stateless logic and perform additional queries.

In summary, the article provides a comprehensive guide for Node.js developers on handling JWT token expiration on logout, combining theoretical explanations with practical code examples.

How to expire JWT token on logout? - Tutorialswebsite (2024)

FAQs

How to expire a JWT token on Logout? ›

To invalidate the JWT token upon logout, you can maintain a blacklist or a list of revoked tokens. When a user logs out, add their token to this blacklist. When a request is made with a blacklisted token, it should be rejected.

How do I invalidate my access token on Logout? ›

Access tokens are valid until the expiration date, and cannot be invalidated. Only refresh tokens can be revoked (invalidated): Revoke Refresh Tokens.

How do I explicitly expire my JWT token? ›

simply follow these 4 bullet points:
  1. Set a reasonable expiration time on tokens.
  2. Delete the stored token from client-side upon log out.
  3. Have DB of no longer active tokens that still have some time to live.
  4. Query provided token against The Blacklist on every authorized request.
Apr 24, 2020

Should JWT be invalidated after logout? ›

However, with JWT tokens, once issued, they remain valid until they expire, regardless of whether a user logs out or not. This can pose a security risk, especially when users want to invalidate their tokens for various reasons, such as logging out from a shared device or changing their password.

How to make a token expire? ›

Go to the Settings tab. Under Refresh Token Expiration, enable Absolute Expiration. When enabled, a refresh token will expire based on an absolute lifetime, after which the token can no longer be used. If rotation is enabled, an expiration lifetime must be set.

How to destroy JWT token on logout in PHP? ›

The token blacklist method is used when creating a logout system. This is one of the ways of invalidating JWTs on logout request. One of the main properties of JWT is that it's stateless and is stored on the client and not in the Database. You don't have to query the database to validate the token.

Are access tokens still valid after logout? ›

Currently, access tokens are valid until they expire regardless of the fact of the user may log out. In terms of security, invalidating access tokens right after the user logs out would reduce the window of opportunity for an attack.

How to invalidate a JWT token after a password change? ›

Hence while invalidating a JWT, follow the below steps,
  1. retrieve the user info and Check whether the token is in his User database. If so allow.
  2. When user logs out, remove only this token from his user database.
  3. When user changes his password, remove all tokens from his user database and ask him to login again.
Feb 27, 2015

Should I revoke refresh token on logout? ›

Yes you should. Because after logout when the user will login a new access token with a new refresh token will be issued. In that case, you should not keep your refresh token. Because whether you delete or not, on next login refresh token will be issued again (if your grant allows).

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

JWTs are self-contained, by-value tokens and it is very hard to revoke them, once issued and delivered to the recipient. Because of that, you should use as short an expiration time for your tokens as possible — minutes or hours at maximum. You should avoid giving your tokens expiration times in days or months.

How to destroy JWT token on logout in spring boot? ›

More how to delete a JWT token? We add a request Id to every JWT token along with the expiration time. When session is created, we persist this request Id, in database, against other token values and its expiry. When server initiates logout, we mark this request as expired.

How to get expiry date from 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.

How to expire a JWT token after logout? ›

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions. JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request.

How many minutes does it take for a JWT token to expire? ›

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.

How often should JWT expire? ›

The API returns a short-lived token (JWT), which expires in 15 minutes, and in HTTP cookies, the refresh token expires in 7 days. JWT is currently used for accessing secure ways on API, whereas a refresh token generates another new JWT access token when it expires or even before.

How to set timeout for JWT token? ›

Approach 1: There exists a key exp in which we can provide the number of seconds since the epoch and the token will be valid till those seconds. // Importing module const jwt = require('jsonwebtoken'); const token = jwt. sign({ // Expression for initialising expiry time exp: Math.

How to automatically log out a user after JWT expires on Angular? ›

JWT expiration counter logic

Then we create a new one, let's start it by passing a fake Observable 'of(null)', from which we'll pipe a delay of exactly the amount of time there's left for the JWT to expire and finally, when this occurs, we call our logout method and rout the user to the login page.

How to get JWT token expiration time? ›

Typically, JWT tokens have an expiration time that is specified in the “exp” (expiration) claim of the 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.

Top Articles
Download The Free Amber App
How cryptocurrency is being used to funnel money to Ukraine
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: Sen. Ignacio Ratke

Last Updated:

Views: 5941

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.