fastapi-jwt-auth
Provides a complete solution for JWT-based authentication in FastAPI applications. Use this skill when a user wants to add secure token-based authentication to their FastAPI project. This skill handles JWT creation, decoding, signature and expiration verification, password hashing, and custom claims. It includes patterns for login endpoints, protected routes using dependencies, role-based access control decorators, token refresh mechanisms, and middleware-based validation.
When & Why to Use This Skill
This Claude skill provides a comprehensive solution for implementing secure JWT (JSON Web Token) authentication within FastAPI applications. It streamlines the process of user identity verification, token management, and role-based access control, ensuring robust security and strict user isolation for modern web APIs by leveraging dependency injection and middleware patterns.
Use Cases
- 1. Securing RESTful APIs: Implementing robust token-based access control to protect sensitive endpoints from unauthorized access.
- 2. User Identity Verification: Automatically extracting and validating user credentials from request headers to maintain session integrity and security.
- 3. Resource Isolation & Ownership: Using path-level validation to ensure that authenticated users can only access or modify resources belonging to their specific user ID.
- 4. Role-Based Access Control (RBAC): Deploying decorators and dependencies to restrict API routes based on user roles and custom claims.
| name | fastapi-jwt-auth |
|---|---|
| description | This skill should be used when implementing secure, reusable JWT verification dependency for FastAPI routes. It ensures strict user isolation and identity verification using Better Auth secrets. |
FastAPI JWT Auth Middleware
This skill provides a secure, reusable JWT verification dependency for FastAPI routes.
Purpose
Implementing a secure, reusable JWT verification dependency for FastAPI routes to ensure strict user isolation and identity verification.
Capabilities
- Extracting
Authorization: Bearer <token>from request headers. - Verifying token signature using the
BETTER_AUTH_SECRETenvironment variable. - Decoding JWT payloads to extract authenticated
user_idandemail. - Performing path-level validation to ensure the authenticated
user_idmatches the{user_id}variable in the route path. - Standardized error handling with
HTTPException:401 Unauthorized: Token missing, invalid signature, or expired.403 Forbidden: Authenticated user ID does not match the requested path resource.
- Providing a
current_userobject injectable directly into route functions.
Implementation Details
Security Pattern
Using python-jose[cryptography] or PyJWT to handle verification.
from fastapi import Depends, HTTPException, status, Request
from jose import jwt
async def get_current_user(user_id: str, request: Request):
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid auth header")
token = auth_header.split(" ")[1]
payload = jwt.decode(token, BETTER_AUTH_SECRET, algorithms=["HS256"])
token_user_id = payload.get("user_id")
if token_user_id != user_id:
raise HTTPException(status_code=403, detail="Not authorized for this resource")
return payload
Best Practices
- Loading
BETTER_AUTH_SECRETonly once at startup. - Always validating the
user_idagainst the path to prevent ID enumeration/access bypass. - Using dependency injection to keep route logic clean and testable.