5. Advanced JWT Architecture
Beyond basic JWT generation, production systems need token revocation, asymmetric signing, and key rotation. This module covers advanced JWT patterns for enterprise applications.
The Problem: JWTs Cannot Be Revoked
Once a JWT is issued, it remains valid until it expires. This is a problem for logout, password changes, and security incidents.
Session-based: Delete session from database → User logged out immediately JWT-based: Token valid until expiration → User still logged in for 15+ minutes
Solution 1: Token Blacklist
Store revoked token IDs in Redis. Check the blacklist on every request.
// When user logs out async function logout(token) { const decoded = jwt.decode(token); const jti = decoded.jti; // Unique token ID const expiresIn = decoded.exp - Math.floor(Date.now() / 1000); // Add to blacklist for remaining lifetime await redis.setex(`blacklist:${jti}`, expiresIn, 'revoked'); } // On every request async function isTokenRevoked(token) { const decoded = jwt.decode(token); const exists = await redis.exists(`blacklist:${decoded.jti}`); return exists === 1; }
Solution 2: Short Access Tokens + Refresh Tokens
The most common approach: access tokens live 15 minutes, refresh tokens live 7 days. Revocation happens at the refresh token level.
Access Token (15 min): Short-lived, minimal damage if stolen Refresh Token (7 days): Long-lived, stored in database, can be revoked When user logs out or changes password: 1. Delete refresh token from database 2. User cannot get new access tokens 3. Existing access tokens expire naturally in 15 minutes
Asymmetric Signing (RS256)
HS256 uses a shared secret — both issuer and verifier need the same secret. In microservices, sharing secrets is risky. RS256 uses a private key to sign and a public key to verify.
HS256 (Symmetric): - One secret key for signing AND verifying - Must share secret with all services - Risk: Secret leak compromises everything RS256 (Asymmetric): - Private key: Used to sign (kept secret by auth service) - Public key: Used to verify (shared with all services) - Safer: Public key leak only allows verification, not forgery
# Generate RSA keys openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -pubout -out public.pem
// Sign with private key (Auth Service) const jwt = require('jsonwebtoken'); const privateKey = fs.readFileSync('private.pem'); const token = jwt.sign({ userId: 123 }, privateKey, { algorithm: 'RS256', expiresIn: '1h' }); // Verify with public key (Any Service) const publicKey = fs.readFileSync('public.pem'); const decoded = jwt.verify(token, publicKey, { algorithms: ['RS256'] });
JWKS: Dynamic Public Key Distribution
JWKS (JSON Web Key Set) allows services to fetch public keys dynamically. This enables key rotation without redeploying services.
// Auth service exposes public keys at this endpoint app.get('/.well-known/jwks.json', (req, res) => { res.json({ keys: [{ kty: 'RSA', use: 'sig', alg: 'RS256', kid: 'key-1', n: 'base64url-modulus', e: 'AQAB' }] }); }); // Other services fetch JWKS and cache it const jwksClient = require('jwks-rsa'); const client = jwksClient({ jwksUri: 'https://auth.myapp.com/.well-known/jwks.json' }); function getKey(header, callback) { client.getSigningKey(header.kid, (err, key) => { callback(null, key.getPublicKey()); }); } jwt.verify(token, getKey, { algorithms: ['RS256'] }, (err, decoded) => { // Token verified using fetched public key });
Knowledge Check
Ready to test your understanding of 5. Advanced JWT Architecture?