Enhancing JWT Security: Server-Side Refresh Token Revocation
Introduction
In modern web applications, JSON Web Tokens (JWTs) are a popular choice for managing user authentication and authorization. While access tokens are typically short-lived, refresh tokens offer a way to obtain new access tokens without requiring users to re-authenticate frequently. However, the long-lived nature of refresh tokens presents a security challenge: how do you invalidate them immediately if a user logs out, changes their password, or if a token is compromised? This post explores the implementation of server-side refresh token revocation using a denylist.
Why Server-Side Revocation?
Client-side revocation alone isn't enough for refresh tokens. Simply deleting a token from the client's storage doesn't prevent a malicious actor from using a stolen token. For critical security events like logout, password reset, or detecting suspicious activity, we need a mechanism to tell the server: "Do not honor this refresh token anymore, even if it's syntactically valid and not expired."
This is where server-side revocation comes in. By maintaining a record of invalidated tokens, the server can actively deny requests attempting to use them.
The Denylist Approach
Our approach uses a 'denylist' (sometimes called a 'blacklist') to track revoked refresh tokens. When a refresh token needs to be invalidated, its unique identifier (JWT ID or jti) is added to this denylist.
Here's how it generally works:
- Unique JTI: Every refresh token must include a unique
jticlaim. Thisjtiacts as the token's fingerprint. - RevokedToken Model: A dedicated data store (e.g., a database table or a Redis instance) holds entries for revoked tokens. Each entry typically includes the
jtiand an expiration timestamp (usually matching the original refresh token's expiration). - Token Revocation Utilities: Functions are needed to:
revokeToken(jti, expiration): Adds ajtito the denylist.isTokenRevoked(jti): Checks if ajtiis present in the denylist.purge(): Periodically cleans up expiredjtientries from the denylist.
Implementing Token Revocation
Integrating the denylist into the authentication flow involves key endpoints:
Refresh Token Rotation
When a user requests a new access token using their refresh token, a process called 'refresh token rotation' is employed:
- The client sends an old refresh token to the
/refresh-tokenendpoint. - The server validates this old refresh token.
- Crucially, the server immediately revokes the old refresh token's
jtiby adding it to the denylist. - A new pair of access and refresh tokens is generated and sent back to the client.
This ensures that each refresh token can only be used once, preventing replay attacks if a token is intercepted.
Logout
When a user logs out, their current refresh token must be invalidated:
- The client sends the refresh token to the
/logoutendpoint. - The server validates the refresh token.
- The refresh token's
jtiis added to the denylist, making it unusable for any future requests.
A Practical Example: Refresh Token Rotation
Consider a simplified Node.js (JavaScript) example demonstrating the core logic for checking and revoking tokens:
// utils/tokenRevocation.js
const revokedTokens = new Set(); // In a real app, this would be a database or Redis
const revokeToken = (jti, expiry) => {
revokedTokens.add(jti);
// In a real app, set a TTL for this JTI based on 'expiry'
console.log(`Token ${jti} revoked until ${new Date(expiry * 1000).toISOString()}`);
};
const isTokenRevoked = (jti) => {
return revokedTokens.has(jti);
};
// Example usage within a refresh endpoint handler
const handleRefreshToken = async (req, res) => {
const oldRefreshToken = req.body.refreshToken;
const decoded = decodeJWT(oldRefreshToken); // Assume decodeJWT extracts jti and expiry
if (isTokenRevoked(decoded.jti)) {
return res.status(401).send('Refresh token already revoked.');
}
// Generate new access and refresh tokens
const newAccessToken = generateAccessToken(decoded.userId);
const newRefreshToken = generateRefreshToken(decoded.userId);
// Revoke the old token's JTI
revokeToken(decoded.jti, decoded.exp);
// In a real app, also persist the new token and associate it with the user
res.json({ accessToken: newAccessToken, refreshToken: newRefreshToken });
};
// Imagine a cron job calls this to clean up expired JTIs
const purgeExpiredTokens = () => {
// Logic to remove JTIs from the 'revokedTokens' storage once their original expiry is passed
console.log('Purging expired revoked tokens...');
};
This example illustrates how a jti is checked against the denylist before allowing a refresh, and then added to it after a successful rotation.
Handling Logout Gracefully
For the /logout endpoint, the flow is even simpler. Upon receiving a logout request with a valid refresh token, we simply extract its jti and add it to our revokedTokens denylist. This immediately invalidates the token, preventing any further use of it.
// Example usage within a logout endpoint handler
const handleLogout = async (req, res) => {
const refreshTokenToRevoke = req.body.refreshToken; // Or from Authorization header
const decoded = decodeJWT(refreshTokenToRevoke);
if (decoded && decoded.jti) {
revokeToken(decoded.jti, decoded.exp);
res.status(200).send('Logged out successfully.');
} else {
res.status(400).send('Invalid refresh token.');
}
};
Conclusion
Implementing server-side refresh token revocation is a critical step towards building a robust and secure authentication system using JWTs. By leveraging a denylist with unique jtis, you gain the ability to immediately invalidate tokens upon user logout, security incidents, or during token rotation, significantly mitigating risks associated with long-lived credentials. This pattern ensures that even if a refresh token is compromised, its lifespan can be cut short, protecting user accounts and application integrity.
Generated with Gitvlg.com