fastapi-jwt-auth
为 FastAPI 应用程序中基于 JWT 的身份验证提供完整的解决方案。当用户想要将基于令牌的安全身份验证添加到其 FastAPI 项目时,请使用此技能。此技能处理 JWT 创建、解码、签名和过期验证、密码散列和自定义声明。它包括登录端点的模式、使用依赖项的受保护路由、基于角色的访问控制装饰器、令牌刷新机制和基于中间件的验证。
📖 中文导读:为 FastAPI 应用程序中基于 JWT 的身份验证提供完整的解决方案。当用户想要将基于令牌的安全身份验证添加到其 FastAPI 项目时,请使用此技能。此技能处理 JWT 创建、解码、签名和过期验证、密码散列和自定义声明。它包括登录端点的模式、使用依赖项的受保护路由、基于角色的访问控制装饰器、令牌刷新机制和基于中间件的验证。 以下正文为该技能的原始 SKILL.md 内容(英文),上方安装命令可直接使用。
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.