auth0-fastapi-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 FastAPI API Integration
Auth0 FastAPI API 集成
Protect FastAPI API endpoints with JWT access token validation using .
auth0-fastapi-apiNote: This SDK is currently in beta. The API surface may change before the stable 1.0 release. Check PyPI for the latest version. Requires Python >= 3.9 and FastAPI >= 0.115.11.
使用通过JWT访问令牌验证保护FastAPI API端点。
auth0-fastapi-api注意: 此SDK目前处于测试版。在稳定的1.0版本发布前,API接口可能会发生变化。请查看PyPI获取最新版本。要求Python >= 3.9 且 FastAPI >= 0.115.11。
Prerequisites
前提条件
- FastAPI application (Python 3.9+)
- Auth0 API resource configured (not an Application — must be an API)
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- FastAPI应用(Python 3.9+)
- 已配置的Auth0 API资源(不是应用程序——必须是API)
- 如果尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
- Server-rendered web applications — Use a session-based login/logout flow instead
- Single Page Applications — Use ,
auth0-react, orauth0-vuefor client-side authauth0-angular - Mobile applications — Use or
auth0-react-nativeauth0-android - Issuing tokens — This skill is for validating access tokens, not issuing them
- 服务端渲染的Web应用 —— 请改用基于会话的登录/登出流程
- 单页应用(SPA) —— 客户端认证请使用、
auth0-react或auth0-vueauth0-angular - 移动应用 —— 请使用或
auth0-react-nativeauth0-android - 签发令牌 —— 本技能用于验证访问令牌,而非签发令牌
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
pip install auth0-fastapi-api python-dotenvbash
pip install auth0-fastapi-api python-dotenv2. Create Auth0 API
2. 创建Auth0 API
You need an API (not Application) in Auth0.
STOP — ask the user before proceeding.Ask exactly this question and wait for their answer before doing anything else:"How would you like to create the Auth0 API resource?
- Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your
automatically..env- Manual — You create the API yourself in the Auth0 Dashboard (or via
) and provide me the Domain and Audience.auth0 apis createWhich do you prefer? (1 = Automated / 2 = Manual)"Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual.
If the user chose Automated, follow the Setup Guide for complete CLI scripts. The automated path writes for you — skip Step 3 below and proceed directly to Step 4.
.envIf the user chose Manual, follow the Setup Guide (Manual Setup section) for full instructions. Then continue with Step 3 below.
Quick reference for manual API creation:
bash
undefined你需要在Auth0中创建一个API(不是应用程序)。
暂停——继续前请询问用户。请准确询问以下问题,等待用户回复后再进行后续操作:"你希望如何创建Auth0 API资源?
- 自动化 —— 我将运行Auth0 CLI脚本创建资源,并自动将准确值写入你的
文件。.env- 手动 —— 你在Auth0控制台(或通过
)自行创建API,并提供Domain和Audience。auth0 apis create你偏好哪种方式?(1 = 自动化 / 2 = 手动)"在用户回复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动化,请遵循设置指南中的完整CLI脚本。自动化流程会为你写入文件——跳过下方步骤3,直接进入步骤4。
.env如果用户选择手动,请遵循设置指南(手动设置章节)中的完整说明。然后继续下方步骤3。
手动创建API的快速参考:
bash
undefinedUsing Auth0 CLI
使用Auth0 CLI
Or create manually in Auth0 Dashboard → Applications → APIs
或在Auth0控制台 → 应用程序 → APIs中手动创建3. Configure Environment
3. 配置环境变量
Create :
.envbash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCE创建文件:
.envbash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCE4. Initialize Auth0
4. 初始化Auth0
python
import os
from fastapi import FastAPI, Depends
from auth0_fastapi_api import Auth0FastAPI
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
auth0 = Auth0FastAPI(
domain=os.getenv("AUTH0_DOMAIN"),
audience=os.getenv("AUTH0_AUDIENCE"),
)Create one instance per application and reuse it across routes. Never hardcode the domain or audience — always use environment variables.
Auth0FastAPIpython
import os
from fastapi import FastAPI, Depends
from auth0_fastapi_api import Auth0FastAPI
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
auth0 = Auth0FastAPI(
domain=os.getenv("AUTH0_DOMAIN"),
audience=os.getenv("AUTH0_AUDIENCE"),
)每个应用创建一个实例,并在所有路由中复用。切勿硬编码域名或受众——始终使用环境变量。
Auth0FastAPI5. Protect Routes
5. 保护路由
python
undefinedpython
undefinedRequire any valid access token
要求任何有效的访问令牌
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
return {"user": claims["sub"]}
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
return {"user": claims["sub"]}
No authentication required
无需认证
@app.get("/api/public")
async def public():
return {"message": "Public endpoint"}
The `require_auth()` dependency validates the Bearer token, verifies the issuer and audience, and returns the decoded JWT claims.
Error responses:
- **400** `invalid_request` — Missing or malformed Authorization header
- **401** `invalid_token` — Expired token, invalid signature, wrong issuer/audience
- **403** `insufficient_scope` — Valid token but missing required scopes
- **500** `internal_server_error` — Unexpected errors
Response body format: `{"detail": {"error": "...", "error_description": "..."}}`@app.get("/api/public")
async def public():
return {"message": "Public endpoint"}
`require_auth()`依赖项会验证Bearer令牌,验证签发者和受众,并返回解码后的JWT声明。
错误响应:
- **400** `invalid_request` —— 缺少或格式错误的Authorization请求头
- **401** `invalid_token` —— 令牌过期、签名无效、签发者/受众错误
- **403** `insufficient_scope` —— 令牌有效但缺少所需权限范围
- **500** `internal_server_error` —— 意外错误
响应体格式:`{"detail": {"error": "...", "error_description": "..."}}`6. Protect Routes with Scope Checks
6. 带权限范围检查的路由保护
python
undefinedpython
undefinedRequires the read:messages scope
需要read:messages权限范围
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
return {"messages": []}
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
return {"messages": []}
Requires both read:data and write:data scopes
需要read:data和write:data权限范围
@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
return {"created": True}
`require_auth(scopes=...)` checks the `scope` claim in the JWT. All specified scopes must be present (AND logic). Missing scopes return **403**.@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
return {"created": True}
`require_auth(scopes=...)`会检查JWT中的`scope`声明。所有指定的权限范围必须存在(逻辑与)。缺少权限范围会返回**403**。7. Access Token Claims
7. 访问令牌声明
The decoded JWT claims are returned directly from the dependency:
python
@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
return {
"sub": claims["sub"], # user ID
"scope": claims.get("scope"), # granted scopes
}Key claims:
- — user/client ID
claims["sub"] - — space-separated granted scopes
claims["scope"] - — issuer (your Auth0 domain URL)
claims["iss"] - — audience
claims["aud"] - — expiration timestamp
claims["exp"] - — issued-at timestamp
claims["iat"]
解码后的JWT声明会直接从依赖项返回:
python
@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
return {
"sub": claims["sub"], # 用户ID
"scope": claims.get("scope"), # 已授予的权限范围
}关键声明:
- —— 用户/客户端ID
claims["sub"] - —— 空格分隔的已授予权限范围
claims["scope"] - —— 签发者(你的Auth0域名URL)
claims["iss"] - —— 受众
claims["aud"] - —— 过期时间戳
claims["exp"] - —— 签发时间戳
claims["iat"]
8. Protect Routes Without Needing Claims
8. 无需获取声明的路由保护
python
@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
return {"message": "You need a valid access token to see this."}python
@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
return {"message": "You need a valid access token to see this."}9. Test the API
9. 测试API
bash
undefinedbash
undefinedNo token — expect 401
无令牌 —— 预期返回401
With a valid access token
使用有效的访问令牌
curl http://localhost:8000/api/private
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab.
---curl http://localhost:8000/api/private
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
通过客户端凭证流程或Auth0控制台 → APIs → 测试标签获取测试令牌。
---Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
Hardcoding | Always read from environment variables — never embed credentials in code |
Using | Not needed; |
Manually parsing | The SDK extracts and validates the token automatically |
Calling | The SDK verifies tokens against the JWKS endpoint — do not verify yourself |
Using | That package is for user management, not Auth0 JWT verification |
| Created an Application instead of an API in Auth0 | Must create an API resource (Applications → APIs) — an Application doesn't issue access tokens with the right audience |
Passing | |
| Using an ID token instead of an access token | Must use the access token for API auth — ID tokens are for the client app, not for API authorization |
| Not configuring CORS for SPA clients | Add |
| Ensure |
| 错误 | 修复方法 |
|---|---|
在代码中硬编码 | 始终从环境变量读取——切勿在代码中嵌入凭证 |
直接使用 | 无需使用; |
手动解析 | SDK会自动提取并验证令牌 |
手动调用 | SDK会针对JWKS端点验证令牌——请勿自行验证 |
使用 | 该包用于用户管理,而非Auth0 JWT验证 |
| 在Auth0中创建了应用程序而非API | 必须创建API资源(应用程序 → APIs)——应用程序不会签发具有正确受众的访问令牌 |
将 | |
| 使用ID令牌而非访问令牌 | API认证必须使用访问令牌——ID令牌用于客户端应用,而非API授权 |
| 未为SPA客户端配置CORS | 添加 |
| 确保已安装 |
DPoP Support
DPoP支持
Built-in proof-of-possession token binding per RFC 9449. DPoP is enabled by default in mixed mode (accepts both Bearer and DPoP tokens). See Integration Guide for configuration.
内置符合RFC 9449的持有证明令牌绑定。DPoP默认以混合模式启用(同时接受Bearer和DPoP令牌)。配置请查看集成指南。
Related Skills
相关技能
- - Basic Auth0 setup and framework detection
auth0-quickstart - - Add Multi-Factor Authentication
auth0-mfa
- - 基础Auth0设置和框架检测
auth0-quickstart - - 添加多因素认证
auth0-mfa
Quick Reference
快速参考
Auth0FastAPI configuration:
python
auth0 = Auth0FastAPI(
domain=os.getenv("AUTH0_DOMAIN"), # required (or use domains)
audience=os.getenv("AUTH0_AUDIENCE"), # required
dpop_enabled=True, # default; set False for Bearer-only
dpop_required=False, # default; set True to reject Bearer tokens
)Route protection:
python
Depends(auth0.require_auth()) # any valid token
Depends(auth0.require_auth(scopes="read:res")) # single scope
Depends(auth0.require_auth(scopes=["r", "w"])) # all scopes requiredAccessing claims:
python
claims["sub"] # user/client ID
claims["scope"] # space-separated scopesEnvironment variables:
- — your Auth0 tenant domain (e.g.
AUTH0_DOMAIN)tenant.us.auth0.com - — your API identifier (e.g.
AUTH0_AUDIENCE)https://api.example.com
Common Use Cases:
- Protect routes → (see Step 5)
Depends(auth0.require_auth()) - Scope enforcement → (see Step 6)
Depends(auth0.require_auth(scopes="...")) - DPoP token binding → Integration Guide
- Reverse proxy setup → Integration Guide
- Advanced configuration → API Reference
Auth0FastAPI配置:
python
auth0 = Auth0FastAPI(
domain=os.getenv("AUTH0_DOMAIN"), # 必填(或使用domains)
audience=os.getenv("AUTH0_AUDIENCE"), # 必填
dpop_enabled=True, # 默认值;设置为False则仅接受Bearer令牌
dpop_required=False, # 默认值;设置为True则拒绝Bearer令牌
)路由保护:
python
Depends(auth0.require_auth()) # 任何有效令牌
Depends(auth0.require_auth(scopes="read:res")) # 单个权限范围
Depends(auth0.require_auth(scopes=["r", "w"])) # 需要所有指定权限范围访问声明:
python
claims["sub"] # 用户/客户端ID
claims["scope"] # 空格分隔的权限范围环境变量:
- —— 你的Auth0租户域名(例如
AUTH0_DOMAIN)tenant.us.auth0.com - —— 你的API标识符(例如
AUTH0_AUDIENCE)https://api.example.com
常见用例:
- 保护路由 → (查看步骤5)
Depends(auth0.require_auth()) - 权限范围强制 → (查看步骤6)
Depends(auth0.require_auth(scopes="...")) - DPoP令牌绑定 → 集成指南
- 反向代理设置 → 集成指南
- 高级配置 → API参考
Detailed Documentation
详细文档
- Setup Guide — Auth0 CLI setup, environment configuration, getting test tokens
- Integration Guide — DPoP, scopes, error handling, reverse proxy, testing
- API Reference — Complete constructor options, method signatures, error codes
- 设置指南 —— Auth0 CLI设置、环境配置、获取测试令牌
- 集成指南 —— DPoP、权限范围、错误处理、反向代理、测试
- API参考 —— 完整的构造函数选项、方法签名、错误代码