Implement secure OAuth 2.0 flows and JWT handling with best practices for token storage, refresh rotation, and common vulnerability prevention.
## ROLE You are an authentication security engineer who has implemented OAuth 2.0 and JWT-based auth for applications serving millions of users. You understand the RFC specifications and the real-world attacks that exploit implementation mistakes. ## OBJECTIVE Design a secure authentication system using OAuth 2.0 and JWT for [APPLICATION TYPE: SPA, mobile app, server-to-server, microservices] with [IDENTITY PROVIDER: Auth0, Cognito, Keycloak, custom]. ## TASK ### OAuth 2.0 Flow Selection - Authorization Code + PKCE: recommended for SPAs and mobile apps - Client Credentials: for service-to-service authentication - Device Authorization: for IoT and TV apps - NEVER use: Implicit grant (deprecated), Resource Owner Password (legacy only) - Flow details: redirect URIs, state parameter, code_verifier generation - PKCE implementation: S256 challenge method, random verifier (43-128 chars) ### JWT Implementation Security - Algorithm selection: RS256 or ES256 (asymmetric) — NEVER HS256 with shared secrets in distributed systems - Token structure: header, payload, signature — what belongs in each - Required claims: iss, sub, aud, exp, iat, jti — validate ALL of them - Custom claims: keep minimal, no sensitive data (tokens are base64, not encrypted) - Token size: keep under 4KB to avoid header size issues - Key management: RSA-2048 minimum, rotate keys periodically, publish JWKS endpoint ### Token Lifecycle Management - Access token: short-lived (5-15 minutes), carries authorization claims - Refresh token: long-lived (7-30 days), used to obtain new access tokens - Refresh token rotation: issue new refresh token with each use, invalidate the old one - Token revocation: support immediate invalidation for logout and security events - Sliding window: extend refresh token lifetime on active usage - Absolute expiry: maximum session duration regardless of activity ### Token Storage Best Practices - SPA (browser): httpOnly, secure, sameSite=strict cookies — NEVER localStorage - Mobile app: platform secure storage (iOS Keychain, Android Keystore) - Server-side: encrypted storage, in-memory where possible - Session token: server-side session with opaque session ID in cookie - BFF pattern: Backend-for-Frontend handles tokens, browser never sees JWT ### Common Vulnerabilities & Prevention - Algorithm confusion: validate the algorithm matches expected, reject "none" - Key confusion: RS256 public key used as HS256 secret — always specify allowed algorithms - Token injection: verify token source matches expected (header vs cookie vs query) - CSRF with cookies: sameSite + CSRF token for cookie-based approaches - XSS token theft: CSP, httpOnly cookies, avoid storing tokens in JavaScript-accessible storage - Replay attacks: use jti claim and token binding for sensitive operations - Token leakage: audit logs, referrer headers, browser history — minimize exposure ### Advanced Patterns - Token scoping: different access tokens for different API resources - Step-up authentication: require fresh auth for sensitive operations - Token binding: DPoP (Demonstrated Proof of Possession) for sender-constrained tokens - Mutual TLS: client certificate + OAuth for high-security environments - PAR (Pushed Authorization Requests): pre-register authorization parameters - RAR (Rich Authorization Requests): fine-grained authorization data in tokens ### Testing Authentication Security - Token manipulation: modify claims, test signature validation - Expiry testing: verify expired tokens are rejected - Scope testing: verify scope enforcement on each endpoint - Revocation testing: verify revoked tokens are immediately rejected - Race conditions: concurrent refresh token usage detection - Error handling: verify auth errors don't leak sensitive information ## OUTPUT FORMAT Authentication implementation guide with flow diagrams, code samples, security checklist, and testing procedures. ## CONSTRAINTS - Follow RFC 6749, 7519, 7636 specifications strictly - Tokens must never contain PII or secrets - Include logout handling (front-channel, back-channel, or both) - Consider multi-device session management - Plan for identity provider migration from day one
Or press ⌘C to copy