How Long is a JWT Token Valid ?

JSON Web Tokens (JWTs) are widely used for authentication and authorization in modern web applications and APIs. One crucial aspect of JWTs is their validity period, which determines how long a token remains valid after it has been issued. In this article, we’ll delve into the factors influencing the validity period of JWT tokens and best practices for setting their expiration time.

Table of Content

  • What is a JWT Token?
  • Importance of Validity Period
  • Factors Influencing Validity Period
  • Best Practices for Setting Validity Period
  • Conclusion

What is a JWT Token?

Before discussing the validity period, let’s briefly review what a JWT token is. A JSON Web Token (JWT) is a compact, URL-safe means of representing claims securely between two parties. It comprises three sections: a header, a payload, and a signature. The payload contains the claims, which are statements about an entity (typically, the user) and additional data. Claims can include information such as the user’s identity, permissions, and expiration time.

Importance of Validity Period

The validity period of a JWT token is crucial for security and access control. It ensures that tokens have a limited lifespan, reducing the risk of unauthorized access if a token is compromised. Setting an appropriate expiration time for JWT tokens is essential for balancing security requirements with user convenience and system performance.

The sign() method of the JSON Webtoken library is used for creating a token that accepts certain information as parameter objects and returns the generated token.  

Syntax:

jwt.sign(payload, secretOrPrivateKey, [options, callback])

Parameters:

  • payload: It is the information to be encrypted in the token
  • secretKey: It is the signature or can say a code that is used to identify the authenticity of the token.
  • options: In the option, we pass certain information about the token and that’s the place where we provide the duration of the token up to which it will be valid.

Return type:

This method will return JWT token

Example: Implementation to create a token with 10 minutes expiry.

Steps to Implement JWT Token with Expiry

Step 1: Create a node project

As we are working on a node library it is a mandatory step to create a node project, write npm init in the terminal. It will ask for a few configurations about your project which is super easy to provide.

npm init

Step 2: Install the “jsonwebtoken” Package

Before going to write the JWT code we must have to install the package, 

npm install jsonwebtoken

This would be our project structure after installation where node_modules contain the modules and package.json stores the description of the project. Also, we have created an app.js file to write the entire code. 

Project Structure:

Step 3: Creating JWT token with a definite expire time.

There are two methods of registering the expiry of the token both are shown below with an explanation. 

  • Creating an expression of an expiry time.
  • Providing expiry time of JWT token in the options argument of the method.

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.

Javascript
// Importing module
const jwt = require('jsonwebtoken');
const token = jwt.sign({

    // Expression for initialising expiry time
    exp: Math.floor(Date.now() / 1000) + (10 * 60),
    data: 'Token Data'
}, 'secretKey');
const date = new Date();
console.log(`Token Generated at:- ${date.getHours()}
                               :${date.getMinutes()}
                               :${date.getSeconds()}`);

// Printing the JWT token
console.log(token);

 Output:

Approach 2: In this method, we can pass the time to expiresIn key in the options, it requires the number of seconds till the token will remain valid or the string of duration as ‘1h’,  ‘2h’, ’10m’, etc.

Javascript
// Importing module
const jwt = require('jsonwebtoken');
const token = jwt.sign({

    // Assigning data value
    data: 'Token Data'
}, 'secretKey', {
    expiresIn: '10m'
});
const date = new Date();
console.log(`Token Generated at:- ${date.getHours()}
                               :${date.getMinutes()}
                               :${date.getSeconds()}`);
// Printing JWT token
console.log(token);
 

Output:

Step 4: Verify the token in terms of expiry duration

We have successfully generated the token now it’s time to verify whether the code is working in its intended way or not. 

Javascript
//Importing module
const jwt = require('jsonwebtoken');
// JWT token
const token = 
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzc4NjgxMzMsImRhdGWf"

const date = new Date();
// Verifying the JWT token 
jwt.verify(token, 'secretKey', function(err, decoded) {
    if (err) {
        console.log(`${date.getHours()}:${date.getMinutes()}
                                       :${date.getSeconds()}`);
        console.log(err);
    }
    else {
        console.log(`${date.getHours()}:${date.getMinutes()}
                                       :${date.getSeconds()}`);
        console.log("Token verifified successfully");
    }
});

Before 10 minutes:

Output 1: Here we are checking before 10 minutes of generating token, as expected the else block of code will work.

After 10 minutes:

Output 2: Here we are checking once the token is expired, the TokenExpirationError will be thrown in this case. 

Factors Influencing Validity Period

Several factors influence the validity period of JWT tokens:

  • Security Requirements: The sensitivity of the data and the security policies of the application or organization influence the choice of token validity period. More sensitive operations may require shorter-lived tokens to minimize the window of vulnerability.
  • Regulatory Compliance: Compliance requirements, such as GDPR (General Data Protection Regulation) in the European Union, may mandate specific data retention and access control practices, including token expiration policies.
  • User Experience: Longer-lived tokens provide a smoother user experience by reducing the frequency of token renewal or reauthentication. However, this convenience must be balanced with security considerations.
  • Token Revocation Mechanisms: The presence of token revocation mechanisms, such as blacklisting or token invalidation, affects the acceptable validity period. Shorter-lived tokens may be preferable when efficient revocation mechanisms are in place.

Best Practices for Setting Validity Period

When setting the validity period of JWT tokens, consider the following best practices:

  • Short-Lived Tokens: Prefer shorter-lived tokens to minimize the risk of unauthorized access in case of token leakage or compromise. Typical expiration times range from minutes to hours, depending on the application’s security requirements.
  • Refresh Tokens: Combine short-lived access tokens with longer-lived refresh tokens. Refresh tokens can be used to obtain new access tokens without requiring the user to reauthenticate, mitigating the impact of short expiration times on user experience.
  • Dynamic Expiration: Implement dynamic expiration policies based on user activity, session context, or access patterns. Extend the expiration time for active sessions while revoking inactive or suspicious tokens promptly.
  • Token Rotation: Periodically rotate JWT tokens and refresh tokens to limit their lifespan and reduce the likelihood of successful token-based attacks.

Conclusion

The validity period of JWT tokens plays a critical role in ensuring the security, compliance, and usability of authentication mechanisms in web applications and APIs. By setting appropriate expiration times and adopting best practices for token management, developers can strike a balance between security requirements and user experience, thereby enhancing the overall resilience and trustworthiness of their systems.