SuperAPI AI 工具集

auth0-fastapi-api

安全与审计

查看项目

更新于 10-15 15:16

技能介绍

用途

auth0-fastapi-api 用于保护 FastAPI API 端点,通过 JWT 访问令牌校验实现无状态 API 的鉴权。它适合需要验证 Bearer 令牌、检查 scope 权限或进行 DPoP 令牌绑定的 FastAPI 后端服务。

注意:该 SDK 目前处于 beta 阶段,稳定版 1.0 发布前 API 接口可能变化,请查看 PyPI 获取最新版本。要求 Python >= 3.9 且 FastAPI >= 0.115.11。

前置条件

  • FastAPI 应用(Python 3.9+)
  • 已在 Auth0 中配置 API 资源(不是 Application,必须是 API)
  • 若尚未设置 Auth0,可先使用 auth0-quickstart 技能

不适用场景

  • 服务端渲染的 Web 应用——应使用基于会话的登录/登出流程
  • 单页应用——应使用 auth0-react、auth0-vue 或 auth0-angular 进行客户端鉴权
  • 移动应用——应使用 auth0-react-native 或 auth0-android
  • 签发令牌——本技能用于校验访问令牌,而非签发令牌

主要能力

  • 通过 require_auth() 依赖校验 Bearer 令牌,验证签发者和受众,返回解码后的 JWT claims
  • 通过 require_auth(scopes=...) 进行 scope 检查,支持单个或多个 scope(AND 逻辑),缺少 scope 返回 403
  • 内置 DPoP 持有证明令牌绑定(RFC 9449),默认以混合模式启用(同时接受 Bearer 和 DPoP 令牌)
  • 提供标准错误响应:400 invalid_request、401 invalid_token、403 insufficient_scope、500 internal_server_error,响应体格式为 {"detail": {"error": "...", "error_description": "..."}}

使用方式

  1. 安装 SDK:pip install auth0-fastapi-api python-dotenv
  2. 在 Auth0 中创建 API 资源(非 Application)。可通过 Auth0 CLI:auth0 apis create --name "My FastAPI API" --identifier https://my-api.example.com,或在 Auth0 Dashboard → Applications → APIs 中手动创建
  3. 配置环境变量:AUTH0_DOMAIN(Auth0 租户域名,不含 https://)和 AUTH0_AUDIENCE(创建 API 资源时设置的 API 标识符)
  4. 初始化:
import os
from fastapi import FastAPI, Depends
from fastapi_plugin import Auth0FastAPI
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),
    audience=os.getenv("AUTH0_AUDIENCE"),
)

每个应用创建一个 Auth0FastAPI 实例并在各路由间复用。切勿硬编码域名或受众,始终使用环境变量。

  1. 保护路由:
# 需要任意有效访问令牌
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {"user": claims["sub"]}

# 无需鉴权
@app.get("/api/public")
async def public():
    return {"message": "Public endpoint"}
  1. 带 scope 检查的路由保护:
# 需要 read:messages scope
@app.get("/api/messages")
async def get_messages(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {"messages": []}

# 需要 read:data 和 write:data 两个 scope
@app.post("/api/data")
async def write_data(claims: dict = Depends(auth0.require_auth(scopes=["read:data", "write:data"]))):
    return {"created": True}
  1. 访问令牌 claims:依赖直接返回解码后的 JWT claims,关键字段包括 claims["sub"](用户/客户端 ID)、claims["scope"](空格分隔的已授予 scope)、claims["iss"](签发者)、claims["aud"](受众)、claims["exp"](过期时间戳)、claims["iat"](签发时间戳)

  2. 不需要 claims 的路由保护:@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])

  3. 测试 API:无令牌请求预期返回 401;带有效访问令牌请求需在请求头添加 Authorization: Bearer YOUR_ACCESS_TOKEN。可通过 Client Credentials 流程或 Auth0 Dashboard → APIs → Test 标签页获取测试令牌。

配置选项

auth0 = Auth0FastAPI(
    domain=os.getenv("AUTH0_DOMAIN"),       # 必填(或使用 domains)
    audience=os.getenv("AUTH0_AUDIENCE"),    # 必填
    dpop_enabled=True,                       # 默认;设为 False 则仅支持 Bearer
    dpop_required=False,                     # 默认;设为 True 则拒绝 Bearer 令牌
)

常见错误

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

相关技能

  • auth0-quickstart——基础 Auth0 设置与框架检测
  • auth0-mfa——添加多因素认证
  • auth0-cli——从终端管理 Auth0 资源

参考

  • auth0-fastapi-api GitHub
  • auth0-fastapi-api on PyPI
  • Auth0 FastAPI API Quickstart
  • FastAPI Dependency Injection
  • Access Tokens Guide