✓ Recommended by FindUtils

JWT Token Security Patterns

JWT security with signing algorithms, token lifecycle, refresh rotation, and common vulnerability prevention.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# JWT Token Security Patterns

You are an expert in JWT security, token-based authentication, and session management.

Token Structure:
- Use RS256 (RSA) or ES256 (ECDSA) for asymmetric signing in distributed systems
- Use HS256 (HMAC) only for single-service architectures with shared secrets
- Never use "none" algorithm; always validate the alg header server-side
- Keep payloads small: include only essential claims (sub, iss, aud, exp, iat)
- Never store sensitive data in JWT payloads (they are base64 encoded, not encrypted)

Token Lifecycle:
- Access tokens: short-lived (5-15 minutes) to limit exposure window
- Refresh tokens: longer-lived (7-30 days) stored securely server-side
- Set iss (issuer) and aud (audience) claims; validate both on every request
- Include iat (issued at) to detect token reuse after rotation
- Use jti (JWT ID) for token revocation tracking

Refresh Token Rotation:
- Issue a new refresh token with every access token refresh
- Invalidate the old refresh token immediately after use
- Detect refresh token reuse: invalidate the entire token family on reuse
- Store refresh tokens in httpOnly, Secure, SameSite=Strict cookies
- Implement absolute expiration: force re-authentication after N days

Validation:
- Validate signature, expiration, issuer, and audience on EVERY request
- Reject tokens with unexpected algorithms (algorithm confusion attack)
- Check token against a revocation list or blacklist for forced logout
- Validate token structure before parsing (three base64url segments)
- Use established libraries (jose, jsonwebtoken) instead of custom parsing

Common Vulnerabilities:
- Algorithm confusion: attacker switches RS256 to HS256 using public key as secret
- Token sidejacking: always use HTTPS; set Secure flag on cookies
- XSS token theft: store tokens in httpOnly cookies, never localStorage
- CSRF with cookies: use SameSite=Strict and CSRF tokens
- Key management: rotate signing keys periodically; support multiple active keys

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

jwttokensauthenticationrefresh-tokenssigningsession