JWT Handler
Overview
Implements secure JWT token lifecycle for web applications — generation, validation, refresh rotation, revocation, and debugging. Produces code that follows current security best practices including short-lived access tokens, one-time refresh rotation with family tracking, and proper key management.
Instructions
Token Generation
When creating JWT tokens:
- Access token: Short-lived (15 min), contains user ID and roles, signed with RS256 or ES256
- Refresh token: Longer-lived (7-30 days), opaque or JWT, stored hashed in database
- Always use asymmetric signing (RS256/ES256) for production — allows verification without the private key
- Minimal payload: user ID, roles, issued-at, expiration. No PII, no secrets.
// Access token payload — keep it minimal
{
sub: "user_abc123",
roles: ["member"],
iat: 1708185600,
exp: 1708186500 // 15 minutes
}
Refresh Token Rotation
Implement one-time rotation with reuse detection:
- Each refresh token belongs to a "family" (first token in chain)
- On refresh: invalidate old token, issue new access + refresh pair
- If a revoked token is presented → revoke ALL tokens in that family (theft detected)
- Store in database: token_hash, family_id, user_id, expires_at, revoked_at
Token Validation Middleware
1. Extract token from Authorization header (Bearer scheme)
2. Verify signature using public key
3. Check expiration (exp claim)
4. Check issuer and audience if configured
5. Attach decoded payload to request context
6. Return 401 with specific error: expired, invalid, missing
Key Management
- Generate RSA 2048+ or EC P-256 key pairs
- Store private key in environment variable or secrets manager
- Expose public key via /.well-known/jwks.json endpoint
- Support key rotation: include key ID (kid) in token header
Examples
Example 1: Node.js Token Service
Prompt: "Create a JWT token service with refresh rotation for my Express app"
Output:
// token.service.ts
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
export class TokenService {
generateAccessToken(user: User): string {
return jwt.sign(
{ sub: user.id, roles: user.roles },
process.env.JWT_PRIVATE_KEY,
{ algorithm: 'RS256', expiresIn: '15m', issuer: 'app' }
);
}
async generateRefreshToken(userId: string, familyId?: string): Promise<string> {
const token = crypto.randomBytes(32).toString('hex');
const hash = crypto.createHash('sha256').update(token).digest('hex');
await db.refreshTokens.create({
tokenHash: hash,
userId,
familyId: familyId || crypto.randomUUID(),
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
});
return token;
}
async rotateRefreshToken(oldToken: string) {
const hash = crypto.createHash('sha256').update(oldToken).digest('hex');
const stored = await db.refreshTokens.findByHash(hash);
if (!stored || stored.revokedAt) {
// Reuse detected — revoke entire family
if (stored) await db.refreshTokens.revokeFamily(stored.familyId);
throw new TokenReuseError();
}
await db.refreshTokens.revoke(stored.id);
const newRefresh = await this.generateRefreshToken(stored.userId, stored.familyId);
const user = await db.users.findById(stored.userId);
const newAccess = this.generateAccessToken(user);
return { accessToken: newAccess, refreshToken: newRefresh };
}
}
Example 2: Debug a JWT Token
Prompt: "This JWT isn't working, can you decode it? eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImV4cCI6MTcwODE4NTYwMH0.abc..."
Output:
Decoded JWT:
Header: { alg: "RS256" }
Payload: { sub: "user_123", exp: 1708185600 }
Issue found: Token expired at 2024-02-17T12:00:00Z (3 hours ago).
The token has no "iat" claim — consider adding it for audit logging.
No "iss" or "aud" claims — recommend adding these for multi-service setups.
Guidelines
- Never use HS256 with a weak secret — use RS256/ES256 or HS256 with 256+ bit random key
- Never store access tokens in localStorage — use memory variables; refresh tokens in httpOnly cookies
- Always hash refresh tokens before database storage — SHA-256 is sufficient
- Include "iat" claim for token age checks and audit logging
- Set clock skew tolerance to 30 seconds for verification across services
- Return specific 401 errors: "token_expired," "token_invalid," "token_missing" — helps client-side handling
1---2name: jwt-handler3description: >-4 When the user needs to generate, validate, refresh, or debug JSON Web Tokens.5 Use when the user mentions "JWT," "access token," "refresh token," "token rotation,"6 "token expiration," "token validation," "bearer token," or "decode JWT."7 Handles secure token lifecycle including signing, verification, refresh rotation,8 and revocation. For full auth system design, see auth-system-setup.9license: Apache-2.010compatibility: "Any language with JWT library support"11metadata:12 source: https://skillmd.com/skills/eliferjunior/jwt-handler13 author: terminal-skills14 version: "1.0.0"15 category: development16 tags: ["jwt", "tokens", "authentication", "security"]17---1819# JWT Handler2021## Overview2223Implements secure JWT token lifecycle for web applications — generation, validation, refresh rotation, revocation, and debugging. Produces code that follows current security best practices including short-lived access tokens, one-time refresh rotation with family tracking, and proper key management.2425## Instructions2627### Token Generation2829When creating JWT tokens:30311. **Access token**: Short-lived (15 min), contains user ID and roles, signed with RS256 or ES256322. **Refresh token**: Longer-lived (7-30 days), opaque or JWT, stored hashed in database333. **Always use asymmetric signing** (RS256/ES256) for production — allows verification without the private key344. **Minimal payload**: user ID, roles, issued-at, expiration. No PII, no secrets.3536```typescript37// Access token payload — keep it minimal38{39 sub: "user_abc123",40 roles: ["member"],41 iat: 1708185600,42 exp: 1708186500 // 15 minutes43}44```4546### Refresh Token Rotation4748Implement one-time rotation with reuse detection:49501. Each refresh token belongs to a "family" (first token in chain)512. On refresh: invalidate old token, issue new access + refresh pair523. If a revoked token is presented → revoke ALL tokens in that family (theft detected)534. Store in database: token_hash, family_id, user_id, expires_at, revoked_at5455### Token Validation Middleware5657```581. Extract token from Authorization header (Bearer scheme)592. Verify signature using public key603. Check expiration (exp claim)614. Check issuer and audience if configured625. Attach decoded payload to request context636. Return 401 with specific error: expired, invalid, missing64```6566### Key Management6768- Generate RSA 2048+ or EC P-256 key pairs69- Store private key in environment variable or secrets manager70- Expose public key via /.well-known/jwks.json endpoint71- Support key rotation: include key ID (kid) in token header7273## Examples7475### Example 1: Node.js Token Service7677**Prompt**: "Create a JWT token service with refresh rotation for my Express app"7879**Output**:80```typescript81// token.service.ts82import jwt from 'jsonwebtoken';83import crypto from 'crypto';8485export class TokenService {86 generateAccessToken(user: User): string {87 return jwt.sign(88 { sub: user.id, roles: user.roles },89 process.env.JWT_PRIVATE_KEY,90 { algorithm: 'RS256', expiresIn: '15m', issuer: 'app' }91 );92 }9394 async generateRefreshToken(userId: string, familyId?: string): Promise<string> {95 const token = crypto.randomBytes(32).toString('hex');96 const hash = crypto.createHash('sha256').update(token).digest('hex');97 await db.refreshTokens.create({98 tokenHash: hash,99 userId,100 familyId: familyId || crypto.randomUUID(),101 expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),102 });103 return token;104 }105106 async rotateRefreshToken(oldToken: string) {107 const hash = crypto.createHash('sha256').update(oldToken).digest('hex');108 const stored = await db.refreshTokens.findByHash(hash);109110 if (!stored || stored.revokedAt) {111 // Reuse detected — revoke entire family112 if (stored) await db.refreshTokens.revokeFamily(stored.familyId);113 throw new TokenReuseError();114 }115116 await db.refreshTokens.revoke(stored.id);117 const newRefresh = await this.generateRefreshToken(stored.userId, stored.familyId);118 const user = await db.users.findById(stored.userId);119 const newAccess = this.generateAccessToken(user);120 return { accessToken: newAccess, refreshToken: newRefresh };121 }122}123```124125### Example 2: Debug a JWT Token126127**Prompt**: "This JWT isn't working, can you decode it? eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImV4cCI6MTcwODE4NTYwMH0.abc..."128129**Output**:130```131Decoded JWT:132 Header: { alg: "RS256" }133 Payload: { sub: "user_123", exp: 1708185600 }134135Issue found: Token expired at 2024-02-17T12:00:00Z (3 hours ago).136The token has no "iat" claim — consider adding it for audit logging.137No "iss" or "aud" claims — recommend adding these for multi-service setups.138```139140## Guidelines141142- **Never use HS256 with a weak secret** — use RS256/ES256 or HS256 with 256+ bit random key143- **Never store access tokens in localStorage** — use memory variables; refresh tokens in httpOnly cookies144- **Always hash refresh tokens** before database storage — SHA-256 is sufficient145- **Include "iat" claim** for token age checks and audit logging146- **Set clock skew tolerance** to 30 seconds for verification across services147- **Return specific 401 errors**: "token_expired," "token_invalid," "token_missing" — helps client-side handling