JSON Web Tokens (JWT) are widely adopted for stateless microservice authentication. However, standard JWT implementations suffer from a critical flaw: once issued, a stateless JWT cannot be revoked before its expiration time unless you implement centralized state tracking.
If an attacker intercepts a long-lived JWT access token, they maintain access to user data until the token expires.
This runbook details an enterprise-grade authentication pattern: Short-Lived Access Tokens paired with Refresh Token Family Rotation and Redis Invalidation Lists.
1. Dual-Token Architectural Blueprint
- Access Token: Lifetime of 15 minutes. Contains user scopes/roles. Transmitted via
Authorization: Bearer <token>headers. Short lifespan minimizes the blast radius of token theft. - Refresh Token: Lifetime of 7 days. Cryptographically secure random UUID stored in a secure,
HttpOnly,SameSite=Strictcookie. Used exclusively to obtain fresh access tokens.
2. Token Family Rotation & Theft Detection Mechanics
Token Rotation mandates that every time a Refresh Token is used, it is invalidated and replaced with a brand-new Refresh Token.
Handling Token Reuse Attack Scenarios:
- Legitimate User (User A) logs in and receives
RefreshToken_V1. - Attacker (User B) steals
RefreshToken_V1. - Attacker exchanges
RefreshToken_V1forRefreshToken_V2.RefreshToken_V1is marked asUSEDin Redis. - Legitimate User later attempts to use
RefreshToken_V1. - System identifies illegal token reuse! The security guard activates: All tokens belonging to that user’s token family are immediately revoked, forcing both the user and the attacker to re-authenticate.
3. Production TypeScript Implementation
TypeScript
import Redis from "ioredis";
import jwt from "jsonwebtoken";
import { v4 as uuidv4 } from "uuid";
const redis = new Redis(process.env.REDIS_URL!);
const JWT_SECRET = process.env.JWT_SECRET!;
interface TokenPayload {
userId: string;
familyId: string;
}
export class AuthTokenManager {
/**
* Generates initial token pair upon login
*/
static async generateTokenPair(userId: string) {
const familyId = uuidv4();
const refreshTokenId = uuidv4();
const accessToken = jwt.sign({ userId, familyId }, JWT_SECRET, { expiresIn: "15m" });
const refreshToken = jwt.sign({ userId, familyId, tokenId: refreshTokenId }, JWT_SECRET, { expiresIn: "7d" });
// Store active refresh token in Redis mapped to its family
await redis.set(
`refresh:${familyId}:${refreshTokenId}`,
"ACTIVE",
"EX",
7 * 24 * 60 * 60
);
return { accessToken, refreshToken };
}
/**
* Rotates refresh tokens securely with theft detection
*/
static async refreshSession(providedRefreshToken: string) {
let payload: any;
try {
payload = jwt.verify(providedRefreshToken, JWT_SECRET);
} catch (err) {
throw new Error("Invalid or expired refresh token.");
}
const { userId, familyId, tokenId } = payload;
const tokenKey = `refresh:${familyId}:${tokenId}`;
const tokenStatus = await redis.get(tokenKey);
// Theft Detection: Token is missing or has already been consumed
if (!tokenStatus || tokenStatus === "USED") {
// Immediate Security Response: Nuke the entire token family
const familyKeys = await redis.keys(`refresh:${familyId}:*`);
if (familyKeys.length > 0) {
await redis.del(...familyKeys);
}
throw new Error("Security Alert: Refresh token reuse detected. All sessions revoked.");
}
// Mark current refresh token as USED (TTL set to 60s to accommodate minor network retries)
await redis.set(tokenKey, "USED", "EX", 60);
// Issue brand-new token pair
const newTokenId = uuidv4();
const newAccessToken = jwt.sign({ userId, familyId }, JWT_SECRET, { expiresIn: "15m" });
const newRefreshToken = jwt.sign({ userId, familyId, tokenId: newTokenId }, JWT_SECRET, { expiresIn: "7d" });
await redis.set(`refresh:${familyId}:${newTokenId}`, "ACTIVE", "EX", 7 * 24 * 60 * 60);
return { accessToken: newAccessToken, refreshToken: newRefreshToken };
}
}


