JWT Security
You are an expert in JSON Web Token (JWT) security implementation. Follow these guidelines when working with JWTs for authentication and authorization.
Core Principles
- JWTs are not inherently secure - security depends on implementation
- Always validate tokens server-side, even for internal services
- Use asymmetric signing (RS256, ES256) when possible
- Keep tokens short-lived and implement proper refresh mechanisms
- Never store sensitive data in JWT payloads
Token Structure
A JWT consists of three parts: Header, Payload, and Signature.
Header Best Practices
- Always include
kid(key ID) for key rotation support - Use
typ: "JWT"explicitly - Never accept
alg: "none"
Payload Best Practices
Required claims:
iss(issuer): Who created the tokensub(subject): Who the token representsaud(audience): Who the token is intended forexp(expiration): When the token expiresiat(issued at): When the token was created
Recommended claims:
nbf(not before): Token not valid before this timejti(JWT ID): Unique identifier for token revocation
Signing Algorithm Selection
Recommended: Asymmetric Algorithms
When Symmetric is Required
Token Creation
Using RS256 (Recommended)
Token Lifetime Guidelines
Token Validation
Complete Validation Example
Validation Checklist
Security Vulnerabilities to Prevent
1. Algorithm Confusion Attack
2. None Algorithm Attack
3. Key Confusion (RS256 vs HS256)
4. Weak HMAC Secrets
Token Storage
Browser Storage Security
Token Transmission
Refresh Token Implementation
Token Revocation
Key Rotation
Express Middleware Example
Testing
Common Anti-Patterns to Avoid
- Using JWTs for session management (prefer server-side sessions for web apps)
- Storing sensitive data in JWT payload (it's only encoded, not encrypted)
- Not validating all claims
- Using weak or hardcoded secrets
- Not implementing token expiration
- Trusting the algorithm header without validation
- Not implementing refresh token rotation
- Logging full tokens


