如何为FastAPI的Swagger UI集成Firebase OAuth2登录?
问题描述
我编写了如下Firebase Auth身份验证中间件,用于从请求头中获取Firebase Token并验证身份:
class AuthenticationMiddleware(BaseHTTPMiddleware): """Middleware to authenticate requests using Firebase Auth.""" async def dispatch(self, request: Request, call_next: Callable): # This is where you can modify the request if needed path = request.url.path # Exclude specific paths from middleware if path in [ "/health", "/auth/login", "/docs", "/openapi.json", ]: return await call_next(request) # Continue with the request headers = request.headers token = headers.get("Authorization") if not token: raise HTTPException(status_code=401, detail="Authorization token is missing") try: # Verify and decode the token using Firebase Admin SDK user_info = auth.verify_id_token(token) # Check if the token is still valid if user_info.get("exp") < time.time(): raise HTTPException(status_code=401, detail="Token expired") # If the token is valid, you can access user information request.state.user = user_info return await call_next(request) # Continue with the request except Exception as err: raise HTTPException(status_code=401, detail="Invalid token") from err
目前所有需要Token验证的API都得用Postman或Thunderclient测试,我想把用户友好的OAuth2登录集成到Swagger UI里简化测试,已经看过FastAPI的Simple OAuth2文档,请教怎么适配现有Firebase中间件实现Swagger内无缝Token测试?
适配方案
要让Swagger UI支持Firebase OAuth2登录,需结合FastAPI安全配置与现有中间件,具体步骤如下:
1. 配置FastAPI的OAuth2安全方案
在FastAPI实例初始化时,添加Swagger OAuth2跳转配置,同时基于Firebase的OpenID Connect(OIDC)规则定义安全方案:
from fastapi import FastAPI from fastapi.security import OAuth2AuthorizationCodeBearer # 替换为你的Firebase项目信息 FIREBASE_PROJECT_ID = "你的Firebase项目ID" FIREBASE_WEB_CLIENT_ID = "你的Firebase Web应用客户端ID" # 定义OAuth2授权码流规则 oauth2_scheme = OAuth2AuthorizationCodeBearer( authorizationUrl="https://accounts.google.com/o/oauth2/v2/auth", tokenUrl=f"https://securetoken.google.com/{FIREBASE_PROJECT_ID}/token", scopes={ "openid": "获取用户身份标识", "email": "获取用户邮箱", "profile": "获取用户基本信息" } ) # 初始化FastAPI并配置Swagger OAuth2参数 app = FastAPI( title="Firebase Auth集成API", swagger_ui_oauth2_redirect_url="/docs/oauth2-redirect", swagger_ui_init_oauth={ "clientId": FIREBASE_WEB_CLIENT_ID, "appName": "你的测试API", "scopes": "openid email profile" } )
2. 调整现有中间件适配Swagger跳转
Swagger登录时会用到/docs/oauth2-redirect路径,需将其加入中间件的排除列表,避免被Token验证拦截:
# 修改中间件的路径排除逻辑 if path in [ "/health", "/auth/login", "/docs", "/openapi.json", "/docs/oauth2-redirect" # 新增该路径 ]: return await call_next(request)
3. 获取Firebase必要配置信息
- Web客户端ID:进入Firebase控制台 → 项目设置 → 应用 → 对应Web应用 → 复制「客户端ID」
- 项目ID:Firebase控制台 → 项目设置 → 常规 → 复制「项目ID」
4. 测试Swagger登录流程
启动FastAPI服务后访问/docs:
- 点击右上角「Authorize」按钮
- 在弹出的授权窗口中完成Firebase账号登录
- 登录成功后,Swagger会自动将Token附加到后续API请求头中,直接点击「Try it out」即可测试受保护的接口
注意:本地测试需使用
http://localhost地址启动服务,否则可能触发跨域拦截;若部署到线上,需确保API地址已加入Firebase项目的授权域名列表。
内容的提问来源于stack exchange,提问作者ProxilityProblemSolver
相关产品推荐
相关产品推荐

