auth0-fastapi-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 FastAPI API Integration

Auth0 FastAPI API 集成

Protect FastAPI API endpoints with JWT access token validation using
auth0-fastapi-api
.
Note: 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
通过JWT访问令牌验证保护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
    auth0-quickstart
    skill first
  • 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
    ,
    auth0-vue
    , or
    auth0-angular
    for client-side auth
  • Mobile applications — Use
    auth0-react-native
    or
    auth0-android
  • Issuing tokens — This skill is for validating access tokens, not issuing them

  • 服务端渲染的Web应用 —— 请改用基于会话的登录/登出流程
  • 单页应用(SPA) —— 客户端认证请使用
    auth0-react
    auth0-vue
    auth0-angular
  • 移动应用 —— 请使用
    auth0-react-native
    auth0-android
  • 签发令牌 —— 本技能用于验证访问令牌,而非签发令牌

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
pip install auth0-fastapi-api python-dotenv
bash
pip install auth0-fastapi-api python-dotenv

2. 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?
  1. Automated — I'll run Auth0 CLI scripts that create the resource and write the exact values to your
    .env
    automatically.
  2. Manual — You create the API yourself in the Auth0 Dashboard (or via
    auth0 apis create
    ) and provide me the Domain and Audience.
Which 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
.env
for you — skip Step 3 below and proceed directly to Step 4.
If 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资源?
  1. 自动化 —— 我将运行Auth0 CLI脚本创建资源,并自动将准确值写入你的
    .env
    文件。
  2. 手动 —— 你在Auth0控制台(或通过
    auth0 apis create
    )自行创建API,并提供Domain和Audience。
你偏好哪种方式?(1 = 自动化 / 2 = 手动)"
在用户回复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动化,请遵循设置指南中的完整CLI脚本。自动化流程会为你写入
.env
文件——跳过下方步骤3,直接进入步骤4。
如果用户选择手动,请遵循设置指南(手动设置章节)中的完整说明。然后继续下方步骤3。
手动创建API的快速参考:
bash
undefined

Using Auth0 CLI

使用Auth0 CLI

auth0 apis create
--name "My FastAPI API"
--identifier https://my-api.example.com

Or create manually in Auth0 Dashboard → Applications → APIs
auth0 apis create
--name "My FastAPI API"
--identifier https://my-api.example.com

或在Auth0控制台 → 应用程序 → APIs中手动创建

3. Configure Environment

3. 配置环境变量

Create
.env
:
bash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com
AUTH0_DOMAIN
is your Auth0 tenant domain (without
https://
).
AUTH0_AUDIENCE
is the API identifier you set when creating the API resource in Auth0.
创建
.env
文件:
bash
AUTH0_DOMAIN=your-tenant.us.auth0.com
AUTH0_AUDIENCE=https://your-api.example.com
AUTH0_DOMAIN
是你的Auth0租户域名(不带
https://
)。
AUTH0_AUDIENCE
是你在Auth0中创建API资源时设置的API标识符。

4. 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
Auth0FastAPI
instance per application and reuse it across routes. Never hardcode the domain or audience — always use environment variables.
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"),
)
每个应用创建一个
Auth0FastAPI
实例,并在所有路由中复用。切勿硬编码域名或受众——始终使用环境变量。

5. Protect Routes

5. 保护路由

python
undefined
python
undefined

Require 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
undefined
python
undefined

Requires 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:
  • claims["sub"]
    — user/client ID
  • claims["scope"]
    — space-separated granted scopes
  • claims["iss"]
    — issuer (your Auth0 domain URL)
  • claims["aud"]
    — audience
  • claims["exp"]
    — expiration timestamp
  • claims["iat"]
    — issued-at timestamp
解码后的JWT声明会直接从依赖项返回:
python
@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
    return {
        "sub": claims["sub"],       # 用户ID
        "scope": claims.get("scope"),  # 已授予的权限范围
    }
关键声明:
  • claims["sub"]
    —— 用户/客户端ID
  • claims["scope"]
    —— 空格分隔的已授予权限范围
  • claims["iss"]
    —— 签发者(你的Auth0域名URL)
  • 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
undefined
bash
undefined

No token — expect 401

无令牌 —— 预期返回401

With a valid access token

使用有效的访问令牌

curl http://localhost:8000/api/private
-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"

通过客户端凭证流程或Auth0控制台 → APIs → 测试标签获取测试令牌。

---

Common Mistakes

常见错误

MistakeFix
Hardcoding
domain
or
audience
in source
Always read from environment variables — never embed credentials in code
Using
python-jose
or
PyJWT
directly
Not needed;
auth0-fastapi-api
handles all validation via JWKS
Manually parsing
Authorization
header
The SDK extracts and validates the token automatically
Calling
jwt.decode()
manually
The SDK verifies tokens against the JWKS endpoint — do not verify yourself
Using
fastapi-users
for Auth0 JWT validation
That package is for user management, not Auth0 JWT verification
Created an Application instead of an API in Auth0Must create an API resource (Applications → APIs) — an Application doesn't issue access tokens with the right audience
Passing
domain
as full URL with
https://
domain
should be the bare domain, e.g.
my-tenant.us.auth0.com
, not
https://my-tenant.us.auth0.com
Using an ID token instead of an access tokenMust use the access token for API auth — ID tokens are for the client app, not for API authorization
Not configuring CORS for SPA clientsAdd
CORSMiddleware
to allow requests from your frontend origin
os.getenv()
returns
None
silently
Ensure
python-dotenv
is installed and
load_dotenv()
is called before
Auth0FastAPI()
initialization — or use
os.environ[]
to fail fast

错误修复方法
在代码中硬编码
domain
audience
始终从环境变量读取——切勿在代码中嵌入凭证
直接使用
python-jose
PyJWT
无需使用;
auth0-fastapi-api
通过JWKS处理所有验证
手动解析
Authorization
请求头
SDK会自动提取并验证令牌
手动调用
jwt.decode()
SDK会针对JWKS端点验证令牌——请勿自行验证
使用
fastapi-users
进行Auth0 JWT验证
该包用于用户管理,而非Auth0 JWT验证
在Auth0中创建了应用程序而非API必须创建API资源(应用程序 → APIs)——应用程序不会签发具有正确受众的访问令牌
domain
作为带
https://
的完整URL传递
domain
应为纯域名,例如
my-tenant.us.auth0.com
,而非
https://my-tenant.us.auth0.com
使用ID令牌而非访问令牌API认证必须使用访问令牌——ID令牌用于客户端应用,而非API授权
未为SPA客户端配置CORS添加
CORSMiddleware
以允许来自前端源的请求
os.getenv()
静默返回
None
确保已安装
python-dotenv
,且在初始化
Auth0FastAPI()
前调用了
load_dotenv()
——或使用
os.environ[]
快速失败

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

相关技能

  • auth0-quickstart
    - Basic Auth0 setup and framework detection
  • auth0-mfa
    - Add Multi-Factor Authentication

  • auth0-quickstart
    - 基础Auth0设置和框架检测
  • 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 required
Accessing claims:
python
claims["sub"]           # user/client ID
claims["scope"]         # space-separated scopes
Environment variables:
  • AUTH0_DOMAIN
    — your Auth0 tenant domain (e.g.
    tenant.us.auth0.com
    )
  • AUTH0_AUDIENCE
    — your API identifier (e.g.
    https://api.example.com
    )
Common Use Cases:
  • Protect routes →
    Depends(auth0.require_auth())
    (see Step 5)
  • Scope enforcement →
    Depends(auth0.require_auth(scopes="..."))
    (see Step 6)
  • 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_DOMAIN
    —— 你的Auth0租户域名(例如
    tenant.us.auth0.com
  • AUTH0_AUDIENCE
    —— 你的API标识符(例如
    https://api.example.com
常见用例:
  • 保护路由 →
    Depends(auth0.require_auth())
    (查看步骤5)
  • 权限范围强制 →
    Depends(auth0.require_auth(scopes="..."))
    (查看步骤6)
  • 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参考 —— 完整的构造函数选项、方法签名、错误代码

References

参考链接