3 Hours
6. Refresh Tokens & Token Rotation
Token Management
Access tokens are short-lived (15-30 minutes) for security, but forcing users to log in every 30 minutes is terrible UX. Refresh tokens solve this: they are long-lived tokens that can obtain new access tokens without re-authentication.
The Two-Token Strategy
Two tokens with different lifetimes and purposes work together.
Text
Access Token (15-30 min): - Sent with every API request - Stateless, fast to verify - Minimal damage if stolen Refresh Token (7-30 days): - Only used to get new access tokens - Stored securely (httpOnly cookie) - Can be revoked (database)
Key Insight: The refresh token is the
master key that can generate many access tokens. Protect it carefully.Login Flow with Refresh Tokens
Text
1. User submits credentials 2. Server validates 3. Server generates: - Access token (15 min, returned in response body) - Refresh token (7 days, set as httpOnly cookie) 4. Client stores access token in memory 5. Client sends access token with every request When access token expires: 1. Client calls /refresh endpoint 2. Server validates refresh token from cookie 3. Server issues new access token 4. Client continues with new token
JavaScript
// Login endpoint app.post('/login', async (req, res) => { const user = await authenticateUser(req.body.email, req.body.password); const accessToken = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '15m' }); const refreshToken = crypto.randomBytes(40).toString('hex'); // Store refresh token hash in database await db.refreshTokens.create({ userId: user.id, tokenHash: crypto.createHash('sha256').update(refreshToken).digest('hex'), expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) }); // Set refresh token as httpOnly cookie res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict' }); res.json({ accessToken }); });
Refresh Endpoint
JavaScript
app.post('/refresh', async (req, res) => { const refreshToken = req.cookies.refreshToken; if (!refreshToken) { return res.status(401).json({ error: 'No refresh token' }); } const tokenHash = crypto.createHash('sha256').update(refreshToken).digest('hex'); const stored = await db.refreshTokens.findOne({ tokenHash, expiresAt: { $gt: new Date() } }); if (!stored) { return res.status(401).json({ error: 'Invalid refresh token' }); } const newAccessToken = jwt.sign({ userId: stored.userId }, SECRET, { expiresIn: '15m' }); res.json({ accessToken: newAccessToken }); });
Security: Refresh tokens are stored as hashes in the database. Even if the database is breached, active refresh tokens are not exposed.
Token Rotation (One-Time Use Refresh Tokens)
For maximum security, make refresh tokens one-time use. Each refresh rotates to a new token, invalidating the old one.
JavaScript
app.post('/refresh', async (req, res) => { const oldToken = req.cookies.refreshToken; const tokenHash = crypto.createHash('sha256').update(oldToken).digest('hex'); const stored = await db.refreshTokens.findOne({ tokenHash }); if (!stored) { return res.status(401).json({ error: 'Invalid refresh token' }); } // ROTATION: Invalidate the old token await db.refreshTokens.deleteOne({ tokenHash }); // Generate new tokens const newAccessToken = jwt.sign({ userId: stored.userId }, SECRET, { expiresIn: '15m' }); const newRefreshToken = crypto.randomBytes(40).toString('hex'); const newTokenHash = crypto.createHash('sha256').update(newRefreshToken).digest('hex'); await db.refreshTokens.create({ userId: stored.userId, tokenHash: newTokenHash, expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) }); res.cookie('refreshToken', newRefreshToken, { httpOnly: true, secure: true, sameSite: 'strict' }); res.json({ accessToken: newAccessToken }); });
Why rotation? If a refresh token is stolen, using it once invalidates it, preventing replay attacks. The legitimate user's next refresh will also fail, alerting them of the compromise.
Logout: Revoking Refresh Tokens
JavaScript
app.post('/logout', async (req, res) => { const refreshToken = req.cookies.refreshToken; if (refreshToken) { const tokenHash = crypto.createHash('sha256').update(refreshToken).digest('hex'); await db.refreshTokens.deleteOne({ tokenHash }); } res.clearCookie('refreshToken'); res.json({ message: 'Logged out successfully' }); });
Also revoke on password change: When a user changes their password, delete ALL their refresh tokens to log out all active sessions.
Knowledge Check
Ready to test your understanding of 6. Refresh Tokens & Token Rotation?