In this lesson, you will learn how to implement "Refresh Token Rotation" to protect your users from session hijacking by issuing a brand new refresh token every time an access token is renewed.
The Problem: Token Longevity
If an attacker steals a long-lived refresh token, they could potentially generate new access tokens indefinitely, maintaining unauthorized access even after the original session should have expired. To mitigate this, we move away from static refresh tokens toward a rotated, single-use model.
The Rotation Mechanism
Instead of simply verifying the old refresh token to issue a new access token, the server now invalidates the current refresh token and issues a new one alongside the access token.
Think of it like a relay race: the refresh token is the baton. Once you use it, you must "hand it off" to get a new one, and the old one is immediately discarded.
// Simplified logic for a rotation endpoint
app.post('/refresh', async (req, res) => {
const { refreshToken } = req.cookies;
// 1. Check if token exists in a whitelist/blacklist in your database
const tokenRecord = await db.findToken(refreshToken);
if (!tokenRecord) {
// SECURITY ALERT: If a used token is presented again,
// it could indicate a theft. Invalidate the whole family!
await db.revokeAllTokensForUser(userId);
return res.status(403).send("Security violation: Token reuse detected.");
}
// 2. Issue a fresh pair
const newAccessToken = generateAccessToken(user);
const newRefreshToken = generateRefreshToken(user);
// 3. Replace old token with the new one in the database
await db.updateToken(refreshToken, newRefreshToken);
res.cookie('refreshToken', newRefreshToken, { httpOnly: true, secure: true });
res.json({ accessToken: newAccessToken });
});
Advanced Security: Handling Reuse
The most powerful aspect of this pattern is Detection. If an attacker manages to steal a token and uses it, the legitimate user will eventually attempt to use the same token (because they haven't seen the server's update yet). When your database sees a refresh token being reused, you know immediately that the session has been compromised. You can then revoke the entire session "family," effectively logging the attacker out and forcing the legitimate user to re-authenticate.
Key Takeaway: Refresh Token Rotation ensures that every refresh token is a single-use credential, effectively containing the window of opportunity for an attacker if a token is ever intercepted.