Keywords: JWT | exp claim | NumericDate | ADAL | token expiration
Abstract: This article provides an in-depth analysis of the exp claim format in JWT, based on the RFC 7519 standard, detailing its representation as a Unix timestamp in seconds. It includes practical code examples for handling the exp claim in the ADAL library and discusses security considerations for JWT expiration settings and refresh token mechanisms.
Format Specification of the JWT exp Claim
According to the RFC 7519 standard, the exp (expiration time) claim in JSON Web Token is encoded in the NumericDate format. This format is defined as the number of seconds since 1970-01-01T00:00:00Z UTC, ignoring leap seconds. It aligns with the POSIX.1 definition of "Seconds Since the Epoch," ensuring consistent time representation across platforms.
Technical Details of NumericDate Format
NumericDate uses integer values to represent timestamps. For example, in the provided Q&A data: iat is 1475874457, and exp is 1475878357. The difference is 1475878357 - 1475874457 = 3900 seconds, i.e., 65 minutes, which matches typical token validity periods, contrary to the initial perception of them being "almost the same."
Handling the exp Claim in ADAL Library
When using the ADAL library to obtain access tokens, the JwtSecurityToken class parses the exp claim as an int32 type. Developers must recognize this value as a Unix timestamp in seconds, not milliseconds or other time units. The following C# code example demonstrates proper conversion:
// Parse JWT token
string tokenString = "your.jwt.token";
var jwtHandler = new JwtSecurityTokenHandler();
var jwtToken = jwtHandler.ReadJwtToken(tokenString);
// Get exp claim value (int32)
var expValue = jwtToken.Payload["exp"];
if (expValue is int expUnixSeconds)
{
// Convert to DateTime (note: DateTimeOffset handles time zones)
DateTime expirationTime = DateTimeOffset.FromUnixTimeSeconds(expUnixSeconds).UtcDateTime;
Console.WriteLine($"Token expires at: {expirationTime}");
}
else
{
Console.WriteLine("Invalid exp claim format");
}Security Practices for JWT Expiration Time
Setting an appropriate exp value requires balancing security and user experience:
- Short-lived tokens (5-15 minutes): Suitable for high-security scenarios like financial services, reducing the time window for token misuse.
- Medium-lived tokens (1-24 hours): Ideal for general web applications, balancing security and convenience.
- Long-lived tokens (7-30 days): Typically used as refresh tokens, requiring secure storage mechanisms.
Refresh Token Mechanism
To mitigate frequent re-authentication due to short-lived tokens, a refresh token mechanism can be employed. The following Node.js example shows how to generate access and refresh tokens:
const jwt = require('jsonwebtoken');
// Generate short-lived access token (15 minutes)
const accessToken = jwt.sign(
{ userId: 123 },
'access_secret',
{ expiresIn: '15m' }
);
// Generate long-lived refresh token (7 days)
const refreshToken = jwt.sign(
{ userId: 123 },
'refresh_secret',
{ expiresIn: '7d' }
);Token Expiration Handling Strategies
When a JWT expires, the system should return a 401 Unauthorized response, prompting the client to use a refresh token for a new access token. If the refresh token is also expired, the user must re-login. The following Express.js middleware example demonstrates token verification logic:
const jwt = require('jsonwebtoken');
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, 'access_secret', (err, user) => {
if (err) {
// Token invalid or expired
return res.sendStatus(403);
}
req.user = user;
next();
});
};Common Pitfalls and Best Practices
Developers often encounter the following issues when handling the exp claim:
- Time unit confusion: Mistaking seconds for milliseconds, leading to incorrect time calculations.
- Long expiration without refresh mechanism: Increases security risks; recommend combining with refresh tokens.
- Difficulty in token revocation: The stateless nature of JWT complicates immediate revocation; token blacklisting (requiring backend storage) can help mitigate this.
Best practices include setting reasonable short expiration times, securely storing refresh tokens in HTTP-only cookies, and invalidating tokens upon user logout.
Conclusion
Accurately understanding and correctly handling the exp claim format in JWT is crucial for building secure authentication systems. By adhering to the RFC 7519 NumericDate specification and implementing appropriate expiration strategies with refresh mechanisms, security can be ensured while optimizing user experience.