如何在FastAPI启动时预填充SwaggerUI的访问令牌?
如何在FastAPI的Swagger UI中预填充Bearer访问令牌?
你尝试通过swagger_ui_parameters配置preauthorizeApiKey来预填充Swagger UI的授权令牌但未生效,核心问题是配置的键与FastAPI生成的安全方案ID不匹配。
解决思路
Swagger UI的preauthorizeApiKey要求键名必须与OpenAPI文档中定义的安全方案ID完全一致。FastAPI默认会为HTTPBearer生成一个自动命名的安全方案ID(比如httpBearer或BearerAuth),而非你写的HTTPBearer,导致配置无法匹配。
方法一:自定义安全方案ID(推荐)
显式指定HTTPBearer的scheme_name参数,让它与preauthorizeApiKey中的键名一致:
from fastapi import Depends, FastAPI, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer # 自定义安全方案ID为"HTTPBearer" security_scheme = HTTPBearer(scheme_name="HTTPBearer") async def verify(token: HTTPAuthorizationCredentials | None = Depends(security_scheme)): # 这里添加令牌验证逻辑 return token app = FastAPI( swagger_ui_parameters={ "preauthorizeApiKey": { "HTTPBearer": "demo_key_for_testing" } } ) @app.get("/api/private") def private(auth_result: HTTPAuthorizationCredentials = Security(verify)): """需要有效访问令牌才能访问的路由""" return {"token": auth_result.credentials}
方法二:匹配自动生成的安全方案ID
如果你不想自定义scheme_name,可以先查看FastAPI自动生成的安全方案ID:
- 启动服务后,访问
/openapi.json路径 - 找到
components -> securitySchemes节点,查看其中的键名(比如httpBearer) - 将该键名填入
preauthorizeApiKey中:
app = FastAPI( swagger_ui_parameters={ "preauthorizeApiKey": { "httpBearer": "demo_key_for_testing" } } )
验证效果
启动服务后打开/docs路径,Swagger UI的授权表单会自动填充demo_key_for_testing作为Bearer令牌,发送请求时会自动带上该令牌。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

