Loading...
Loading...
Compare original and translation side by side
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.
auth0-fastapi-api注意: 此SDK目前处于测试版。在稳定的1.0版本发布前,API接口可能会发生变化。请查看PyPI获取最新版本。要求Python >= 3.9 且 FastAPI >= 0.115.11。
auth0-quickstartauth0-quickstartauth0-reactauth0-vueauth0-angularauth0-react-nativeauth0-androidauth0-reactauth0-vueauth0-angularauth0-react-nativeauth0-androidpip install auth0-fastapi-api python-dotenvpip install auth0-fastapi-api python-dotenvSTOP — 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.
.envundefined暂停——继续前请询问用户。请准确询问以下问题,等待用户回复后再进行后续操作:"你希望如何创建Auth0 API资源?
- 自动化 —— 我将运行Auth0 CLI脚本创建资源,并自动将准确值写入你的
文件。.env- 手动 —— 你在Auth0控制台(或通过
)自行创建API,并提供Domain和Audience。auth0 apis create你偏好哪种方式?(1 = 自动化 / 2 = 手动)"在用户回复前,请勿进行任何设置步骤。请勿默认选择手动方式。
.envundefined
Or create manually in Auth0 Dashboard → Applications → APIs
或在Auth0控制台 → 应用程序 → APIs中手动创建.envAUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCE.envAUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.comAUTH0_DOMAINhttps://AUTH0_AUDIENCEimport 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"),
)Auth0FastAPIimport 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"),
)Auth0FastAPIundefinedundefined
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": "..."}}`
`require_auth()`依赖项会验证Bearer令牌,验证签发者和受众,并返回解码后的JWT声明。
错误响应:
- **400** `invalid_request` —— 缺少或格式错误的Authorization请求头
- **401** `invalid_token` —— 令牌过期、签名无效、签发者/受众错误
- **403** `insufficient_scope` —— 令牌有效但缺少所需权限范围
- **500** `internal_server_error` —— 意外错误
响应体格式:`{"detail": {"error": "...", "error_description": "..."}}`undefinedundefined
`require_auth(scopes=...)` checks the `scope` claim in the JWT. All specified scopes must be present (AND logic). Missing scopes return **403**.
`require_auth(scopes=...)`会检查JWT中的`scope`声明。所有指定的权限范围必须存在(逻辑与)。缺少权限范围会返回**403**。@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
}claims["sub"]claims["scope"]claims["iss"]claims["aud"]claims["exp"]claims["iat"]@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
return {
"sub": claims["sub"], # 用户ID
"scope": claims.get("scope"), # 已授予的权限范围
}claims["sub"]claims["scope"]claims["iss"]claims["aud"]claims["exp"]claims["iat"]@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
return {"message": "You need a valid access token to see this."}@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
return {"message": "You need a valid access token to see this."}undefinedundefined
Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab.
---
通过客户端凭证流程或Auth0控制台 → APIs → 测试标签获取测试令牌。
---| 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 | 添加 |
| 确保已安装 |
auth0-quickstartauth0-mfaauth0-quickstartauth0-mfaauth0 = 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
)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 requiredclaims["sub"] # user/client ID
claims["scope"] # space-separated scopesAUTH0_DOMAINtenant.us.auth0.comAUTH0_AUDIENCEhttps://api.example.comDepends(auth0.require_auth())Depends(auth0.require_auth(scopes="..."))auth0 = Auth0FastAPI(
domain=os.getenv("AUTH0_DOMAIN"), # 必填(或使用domains)
audience=os.getenv("AUTH0_AUDIENCE"), # 必填
dpop_enabled=True, # 默认值;设置为False则仅接受Bearer令牌
dpop_required=False, # 默认值;设置为True则拒绝Bearer令牌
)Depends(auth0.require_auth()) # 任何有效令牌
Depends(auth0.require_auth(scopes="read:res")) # 单个权限范围
Depends(auth0.require_auth(scopes=["r", "w"])) # 需要所有指定权限范围claims["sub"] # 用户/客户端ID
claims["scope"] # 空格分隔的权限范围AUTH0_DOMAINtenant.us.auth0.comAUTH0_AUDIENCEhttps://api.example.comDepends(auth0.require_auth())Depends(auth0.require_auth(scopes="..."))