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

如何用Azure AD(fastapi_msal)实现FastAPI /docs端点弹窗授权登录

实现FastAPI Docs端点与Azure AD的登录集成(基于fastapi_msal)

1. 安装依赖

先安装所需Python包:

pip install fastapi fastapi_msal uvicorn python-multipart

2. 配置Azure AD应用

在Azure Active Directory中完成以下操作:

  • 注册新应用,获取客户端ID和租户ID
  • 设置重定向URI为http://localhost:8000/docs/oauth2-redirect(对应Swagger UI的OAuth2回调地址)
  • 启用隐式授权流(勾选ID令牌和访问令牌选项)
  • 添加必要API权限(例如User.Read)并授予管理员同意

3. 编写FastAPI应用代码

替换原有的OAuth2PasswordBearer逻辑,改用fastapi_msal实现Azure AD集成:

from fastapi import FastAPI, Depends
from fastapi_msal import MSALClient, User

# 初始化FastAPI应用
app = FastAPI(
    title="Azure AD Auth Demo",
    # 配置Swagger UI的OAuth2参数,让Authorize按钮触发弹窗
    swagger_ui_init_oauth={
        "clientId": "你的Azure AD客户端ID",
        "scopes": ["User.Read"],
        "usePkceWithAuthorizationCodeGrant": True
    }
)

# 初始化MSAL客户端
msal_client = MSALClient(
    client_id="你的Azure AD客户端ID",
    tenant_id="你的Azure AD租户ID",
    scopes=["User.Read"],
    redirect_uri="http://localhost:8000/docs/oauth2-redirect"
)

# 受保护的示例端点
@app.get("/protected")
def protected_route(current_user: User = Depends(msal_client.get_current_user)):
    return {"message": f"Hello, {current_user.name}!", "user_info": current_user.dict()}

4. 关键配置说明

  • swagger_ui_init_oauth:配置后Swagger UI的Authorize按钮会直接调用Azure AD登录弹窗,无需手动输入令牌
  • MSALClient:自动处理令牌的获取、Cookie存储和验证,后续请求会自动携带Cookie中的令牌,无需前端额外处理
  • 替换原OAuth2PasswordBearer:用msal_client.get_current_user作为依赖项,自动验证请求令牌,确保仅登录用户可访问受保护端点

5. 测试流程

  1. 启动应用:uvicorn main:app --reload
  2. 访问http://localhost:8000/docs,点击右上角Authorize按钮
  3. 弹出Azure AD登录窗口,输入账号密码完成登录
  4. 登录成功后,Swagger UI会自动将令牌附加到后续API请求,直接测试受保护端点即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:35:08