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

FastAPI OAuth2隐式流:获取AccessToken后API请求未携带令牌

解决FastAPI OAuth2隐式流中Swagger UI不自动携带Access Token的问题

问题核心

已成功通过Azure AD获取Access Token并存入浏览器localStorage,但Swagger UI发起的API请求(包括生成的curl命令)未自动携带该令牌,授权按钮显示正常但实际未生效。

关键原因

当前重定向页面的OAuth2回调参数格式不符合Swagger UI的预期,Swagger需要包含access_token和token_type的结构化对象才能识别并自动携带令牌。

解决方案

1. 修改重定向页面的回调逻辑

调整重定向HTML中的脚本,确保传递给Swagger的token对象结构正确,同时让Swagger能读取到授权信息:

html = """
    <!doctype html>
    <html lang="en-US">
    <head>
        <title>Swagger UI: OAuth2 Redirect</title>
    </head>
    <body>
    <script>
        'use strict';
        function run() {
            var oauth2 = window.opener.swaggerUIRedirectOauth2;
            var sentState = oauth2.state;
            var redirectUrl = oauth2.redirectUrl;
            var isValid;

            // 提取URL片段中的参数
            var fragment = window.location.hash.substring(1);
            var params = new URLSearchParams(fragment);

            var accessToken = params.get('access_token');
            isValid = params.get('state') === sentState;

            // 存储完整的授权对象到localStorage,方便Swagger读取
            var authData = {
                token: {
                    access_token: accessToken,
                    token_type: "Bearer"
                }
            };
            localStorage.setItem('swagger-oauth2-authentication', JSON.stringify(authData));

            // 按Swagger期望的格式回调
            oauth2.callback({
                auth: oauth2.auth,
                token: {
                    access_token: accessToken,
                    token_type: "Bearer"
                },
                isValid: isValid,
                redirectUrl: redirectUrl
            });

            window.close()
        }

        if (document.readyState !== 'loading') {
            run();
        } else {
            document.addEventListener('DOMContentLoaded', run);
        }
    </script>
    </body>
    </html>
        """

2. 配置Swagger UI持久化授权

在FastAPI应用初始化时,开启Swagger UI的授权持久化,让它自动读取localStorage中的授权信息:

from fastapi import FastAPI, HTMLResponse
from fastapi.openapi.docs import get_swagger_ui_html

app = FastAPI(docs_url=None, redoc_url=None)

# 自定义Swagger UI路由,开启持久化授权
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url="/oauth2-redirect",
        swagger_ui_init_oauth={
            "persistAuthorization": True,
            "clientId": "你的Azure AD客户端ID",
            "scopes": "你的API权限范围"
        }
    )

# 你的OAuth2重定向路由
@app.get("/oauth2-redirect", include_in_schema=False)
async def oauth2_redirect():
    return HTMLResponse(html)

3. 验证效果

  • 重启FastAPI服务
  • 访问/docs,重新完成Azure AD授权流程
  • 调用受保护接口时,查看生成的curl命令,应该会包含Authorization: Bearer <你的token>头:
curl -X 'GET' \
  'http://localhost:8000/protected' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6...'

额外检查点

  • 确认FastAPI的OAuth2依赖配置正确,比如使用OAuth2AuthorizationCodeBearer并正确设置authorizationUrl和tokenUrl
  • 确保Azure AD应用注册的重定向URI与FastAPI的/oauth2-redirect完全匹配
  • 检查浏览器控制台是否有JS错误,排查token获取和存储过程中的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:35:37