Implement Secure Authentication Middleware with JWT and Role-Based Access Control

Build secure JWT authentication middleware with refresh tokens, RBAC, and security best practices for your API framework.

๐Ÿ“ The Prompt

Write a complete authentication and authorization middleware for a [FRAMEWORK] application (e.g., Express.js, FastAPI, Spring Boot, Laravel) in [PROGRAMMING_LANGUAGE]. The middleware should handle JWT-based authentication with role-based access control (RBAC) and meet these specifications: 1. **JWT Token Handling**: - Extract the JWT from the Authorization header (Bearer scheme) and optionally from an HTTP-only cookie named [COOKIE_NAME]. - Verify the token signature using [ALGORITHM] (e.g., RS256 or HS256) with a secret/key stored in environment variables. - Decode the payload and attach the authenticated user object to the request context. - Handle token expiration gracefully with clear error messages. 2. **Token Refresh Flow**: - Implement a refresh token mechanism. Access tokens should expire in [ACCESS_TOKEN_TTL] and refresh tokens in [REFRESH_TOKEN_TTL]. - Include a middleware or utility function that issues new access/refresh token pairs and rotates the refresh token on each use (to detect token reuse/theft). 3. **Role-Based Access Control**: - Define roles: [ROLES_LIST] (e.g., admin, editor, viewer, user). - Create a `requireRole(...roles)` middleware/decorator that restricts route access to users with the specified roles. - Create a `requirePermission(...permissions)` middleware/decorator for fine-grained permission checks (e.g., 'posts:write', 'users:delete'). 4. **Security Best Practices**: - Protect against common attacks: add rate limiting on auth endpoints, prevent timing attacks in token comparison, and sanitize error messages to avoid leaking information. - Include CSRF protection strategy for cookie-based auth. - Log authentication failures with IP address and timestamp for audit purposes. 5. **Error Handling**: Return standardized JSON error responses with appropriate HTTP status codes (401 for unauthenticated, 403 for unauthorized) following [API_STYLE] conventions (e.g., REST, JSON:API). 6. **Integration Example**: Show how to apply the middleware to three sample routes โ€” a public route, an authenticated route, and an admin-only route. Provide complete, production-quality code with comments explaining security decisions. Include a list of required environment variables and npm/pip/maven dependencies.

๐Ÿ’ก Tips for Better Results

Specify whether you prefer RS256 (asymmetric, better for microservices) or HS256 (simpler, single-service) so the key management code matches your architecture. Include your actual role and permission names so the generated code reflects your real authorization model. Ask the AI to also generate matching unit tests for edge cases like expired tokens, malformed headers, and insufficient permissions.

๐ŸŽฏ Use Cases

Full-stack and backend developers who need to add robust authentication and authorization to an API, especially when building SaaS products or multi-tenant applications.

๐Ÿ”— Related Prompts

๐Ÿ’ป Coding beginner

Explain Code Like Im a Beginner

Get any code explained in plain English with line-by-line breakdowns, analogies, and learning suggestions.

๐Ÿ’ป Coding beginner

Debug My Code and Explain the Fix

Get your code debugged with clear explanations of what went wrong and why, plus the corrected version.

๐Ÿ’ป Coding intermediate

Write Unit Tests for My Code

Generate thorough unit tests covering edge cases, error handling, and both positive and negative scenarios.

๐Ÿ’ป Coding intermediate

Convert Code Between Languages

Convert code between any programming languages while maintaining idiomatic patterns and best practices.

๐Ÿ’ป Coding intermediate

Write a REST API Endpoint

Generate production-ready REST API endpoints with validation, error handling, and documentation.

๐Ÿ’ป Coding advanced

Refactor Code for Better Performance

Get your code refactored for better performance with Big O analysis and design pattern suggestions.