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)
Top Articles
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.