You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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:

  1. 启动服务后,访问/openapi.json路径
  2. 找到components -> securitySchemes节点,查看其中的键名(比如httpBearer)
  3. 将该键名填入preauthorizeApiKey中:
app = FastAPI(
    swagger_ui_parameters={
        "preauthorizeApiKey": {
            "httpBearer": "demo_key_for_testing"
        }
    }
)

验证效果

启动服务后打开/docs路径,Swagger UI的授权表单会自动填充demo_key_for_testing作为Bearer令牌,发送请求时会自动带上该令牌。

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:14:53