Generate a secure JWT authentication implementation with refresh tokens, token rotation, blacklisting, and attack prevention.
You are a security architect specializing in authentication. Build a hardened JWT authentication system. ## Configuration - **Language/Framework**: [FRAMEWORK e.g. Node.js Express / Python FastAPI / .NET Core / Go Gin] - **Token Storage**: [STORAGE e.g. httpOnly cookies / localStorage / memory] - **Database**: [DB e.g. PostgreSQL / MongoDB / Redis] - **Requirements**: [REQS e.g. SSO support / multi-device / API-only] ## Implementation ### 1. Token Generation (`auth/tokens.py`) - Access token: - Algorithm: RS256 (asymmetric) or EdDSA - Expiry: [ACCESS_TTL e.g. 15 minutes] - Claims: sub, iat, exp, jti (unique ID), roles, permissions - Audience and issuer validation - Refresh token: - Opaque token (not JWT) stored in [DB] - Expiry: [REFRESH_TTL e.g. 30 days] - Bound to device fingerprint - One-time use with rotation - Token family tracking for refresh token reuse detection ### 2. Key Management (`auth/keys.py`) - RSA/Ed25519 key pair generation and rotation - JWKS (JSON Web Key Set) endpoint - Key rotation schedule with overlap period - Key storage: environment variables or vault integration - Key ID (kid) in JWT header for multi-key support ### 3. Security Middleware (`middleware/auth.py`) - Token extraction from Authorization header or httpOnly cookie - Signature verification with key rotation support - Claims validation: exp, nbf, iss, aud - JTI blacklist check (for revoked tokens) - Rate limiting on authentication endpoints - Brute force protection with progressive delays ### 4. Refresh Flow (`auth/refresh.py`) - Automatic token rotation on refresh - Invalidate entire token family on reuse detection - Device tracking with user-agent and IP - Concurrent session limiting per user - Graceful expiry with refresh-ahead pattern ### 5. Attack Prevention - **Algorithm confusion**: reject 'none', enforce expected algorithm - **Key confusion**: strict RS256 key type validation - **Token injection**: validate token structure before parsing - **Replay attacks**: JTI tracking with short-lived tokens - **CSRF**: SameSite=Strict cookies, CSRF tokens for cookie-based auth - **XSS mitigation**: httpOnly, Secure, SameSite cookie flags - **Token leakage**: never log tokens, mask in error responses ### 6. Session Management (`auth/sessions.py`) - Active session listing per user - Remote session revocation - Session activity tracking - Forced logout on password change - Admin session management dashboard Provide complete implementation with tests covering all attack vectors.
Free to copy and use. Compatible with Claude 4 Opus, GPT-5, Gemini 2.0 Flash, Llama 4 Maverick.
Choose your framework and token storage strategy. Implement key management first, then token generation and validation. Test all attack prevention measures with the included test suite.
Initial release
Sign in and download this prompt to leave a review.