How to Manage Expired JWT Tokens and Keep Users Logged In

How to Manage Expired JWT Tokens and Keep Users Logged In

Using Access and Refresh Tokens

ยท

6 min read

Introduction

JWT (JSON Web Tokens) has become a popular authentication mechanism for web applications due to its stateless nature and flexibility. However, one challenge developers face is managing expired JWT tokens while keeping users logged in seamlessly. In this article, we will explore best practices for handling expired JWT tokens and maintaining persistent user login, ensuring a smooth user experience without compromising security.

What is a JWT token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained format for securely transmitting information between parties as a JSON object. It can be encoded with user information like id, name, email etc which can be used in web applications and APIs to handle authentication and authorization.

What is an Access token?

An access token is a credential used in authentication and authorization processes to grant a user access to protected API routes or resources. It is also called a "bearer" token because it is passed along with each API request as proof of authentication, similar to how a person holding a valid ticket is granted entry to an event. The bearer token is typically included in the "Authorization" header of an HTTP request with the prefix "Bearer", followed by the token value.

Generally, such tokens get expire after some time (which is set by the developer). Due to the token's expiration, the user will get an unauthenticated response ie error code 401. So the question arises What is the need for the Expiry of tokens and How to handle expired tokens? Here is the step-by-step guide.

1. Keep Expiry Time too high (Least secured):

One thing I noticed every developer suggests that keep a long expiry time like 6 months, 1 year, or to the end of eternity :). But this is not recommended as it can introduce security risks.

Why is JWT token expiration important?

The expiration time of JWT tokens is important in preventing unauthorized access by minimizing the window of opportunity for attackers to exploit stolen tokens. With the concept of Bearer tokens, if a token is stolen, an attacker can gain access to user data and resources on the server. Therefore, it is crucial to have an expiration time for tokens that strikes a balance between the desired security level and user experience, taking into account the available resources.

2. Logout after the Expiration

This approach provides enhanced security compared to the previous one, but it may negatively impact the user experience of the app. Requiring users to log in each time the token expires can be cumbersome, and many people prefer to avoid the additional login screen. Therefore, this may not be the most favorable solution in terms of usability.

3. Implement Token Refresh Mechanism (Enhanced Security and User Experience):

This is one of the best solutions to manage the expired Access Token. It uses an additional token called Refresh Token.

What is a Refresh Token?

A refresh token is a concept used in authentication systems to extend the validity of an access token without requiring the user to re-authenticate. While access tokens have a short expiration time to enhance security, refresh tokens have a longer lifespan. When the access token expires, the refresh token can be used to obtain a new access token.

I would say this will solve the problem but partially. Some questions will still arise:

A. Can't we keep a check for the expiry time?

Implementing the Refresh Mechanism with the same token and running a background check to verify its validity periodically is an alternative approach. However, it comes with certain drawbacks that can significantly impact resource usage and potentially lead to battery drainage, particularly in mobile apps.

By continuously running a background process to check the token's validity, the application would need to consume additional resources and maintain a constant connection to the server. This continuous activity can result in increased CPU usage, and heightened network activity, and potentially drain the device's battery more quickly.

Similarly, constantly checking for the expiry of the Refresh Token can also lead to these same consequences.

B. What if Refresh Token is Stolen?

We have come to understand the consequences of someone stealing a user's Access Token. The same holds true for the Refresh Token. With a Refresh Token, an individual can easily request an Access Token from the server. This poses a significant security risk as unauthorized access to the user's account can be gained using the stolen Refresh Token.

There can be many such questions. Keeping these in mind. We can move forward to the best solution we can have.

4. Use of 'One Time Use' Refresh Token with no expiry time

In this solution, we will be using a one-time-use Refresh Token and there will be no expiry time for the token. This token can be stored in the browser's local storage and also there will be a track of the token in the database. If a token is once used it will be provoked for further use and the new token will be generated and sent back to the user.

In simple terms, while requesting for the Access token the user will get a new Access Token and a new Refresh Token.

When to Use the Refresh Token?

We utilize the Refresh Token when the Access Token has expired, eliminating the need for continuous background checks. This approach proves useful during a session when API calls return a 401 unauthorized error due to an expired Access Token.

What if Refresh Token is stolen?

If the Refresh Token is leaked after use, there is no significant risk. This is because the server performs a check to determine if the token has already been used. Therefore, even if an attacker gains access to the leaked Refresh Token, they cannot exploit it.

However, if an unused Refresh Token is stolen, the situation changes. In this case, it is necessary to invalidate all existing sessions and redirect users to log in again whenever a used token is sent back to the server. This precaution ensures that the real user is prompted to reauthenticate since their token has already been used by the attacker.

Code Example

Generate JWT Access Token

Generate Refresh Token

Revoke Refresh Token

Get New Access Token API Route

Flow Diagram

Conclusion

Managing expired JWT tokens is crucial for maintaining a secure and seamless user login experience. Implementing a token refresh mechanism with a one-time-use Refresh Token is a recommended solution. This approach extends token validity without requiring reauthentication and enhances security. However, it's important to address concerns such as token validity checks and the risk of token theft. By finding the right balance between security and user experience, web applications can ensure a smooth authentication process while keeping user data protected.

What Next?

It was a significant challenge in one of our apps, and I conducted thorough research to find the best solutions. Sharing these findings can be valuable for other developers facing similar issues. While the solution I proposed may not be perfect, I believe it provides a solid foundation. I welcome your valuable suggestions, bug reports, and queries in the comments section.

If you found the content useful, please like ๐Ÿ‘ the blog and consider sharing it with your fellow developers.

Thank you for reading! ๐Ÿ’ซโœจ

ย