Backend · Architecture & Multi-Tenancy· 8 min read
JWT cookie authentication: httpOnly tokens, silent refresh, and session revocation
Why storing JWTs in localStorage is an XSS vulnerability. How to implement secure httpOnly cookies, silent token rotation, CSRF protection, and Redis-backed session revocation.
AuthenticationSecurityJWTCookiesRedisNestJS
The web is full of tutorials telling developers to store JWT tokens in browser `localStorage`. In enterprise applications, this is an automatic security audit failure. Any third-party npm package, CDN script, or Cross-Site Scripting (XSS) vulnerability can immediately execute `localStorage.getItem('token')` and exfiltrate credentials without the user ever noticing. In our platforms, authentication is built exclusively on secure, httpOnly, sameSite cookies with silent refresh token rotation.
The dual-token cookie strategy
| Token Type | Lifetime | Storage Location | Purpose |
|---|---|---|---|
| Access Token | 15 minutes | httpOnly, Secure, SameSite=Lax Cookie | Authorizes API requests. Short expiration limits window of stolen tokens. |
| Refresh Token | 7 days | httpOnly, Secure, SameSite=Strict Cookie | Exchanged for new access token at `/auth/refresh`. Stored with hash in Redis. |
import { Response } from 'express';
export function attachAuthCookies(res: Response, accessToken: string, refreshToken: string) {
const isProd = process.env.NODE_ENV === 'production';
res.cookie('access_token', accessToken, {
httpOnly: true,
secure: isProd,
sameSite: 'lax',
path: '/',
maxAge: 15 * 60 * 1000, // 15 minutes
});
res.cookie('refresh_token', refreshToken, {
httpOnly: true,
secure: isProd,
sameSite: 'strict',
path: '/api/auth/refresh', // Scoped exclusively to refresh endpoint
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
});
}Silent refresh rotation and token reuse detection
Every time a refresh token is presented, it is immediately invalidated and replaced with a new refresh token family. If an attacker attempts to replay an old refresh token, our Redis guard detects duplicate submission, immediately revokes the entire token family, and forces all active sessions for that user account to log out.
export async function rotateRefreshToken(userId: string, incomingToken: string) {
const storedHash = await redisClient.get(`session:${userId}:refresh`);
// Token reuse detected! Someone is replaying an already-consumed token.
if (!storedHash || storedHash !== hashToken(incomingToken)) {
await redisClient.del(`session:${userId}:refresh`);
throw new UnauthorizedException('Security alert: Token reuse detected. Session terminated.');
}
const newAccessToken = signAccessToken(userId);
const newRefreshToken = generateSecureRandomToken();
await redisClient.set(
`session:${userId}:refresh`,
hashToken(newRefreshToken),
'EX',
7 * 86400
);
return { accessToken: newAccessToken, refreshToken: newRefreshToken };
}