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

Python开发MS Teams聊天机器人获取AccessToken遇MFA及重定向URI问题求助

问题分析与解决方案

核心问题原因

  • acquire_token_by_username_password(ROPC用户名密码流程)不支持多因素认证(MFA),当你的用户账号被管理员强制要求MFA时,必然触发AADSTS50076错误,这是该流程的设计限制。
  • 浏览器登录时的重定向URI错误,是因为交互式认证流程(如授权码流程)必须在Azure应用注册中配置对应重定向URI,你当前未配置导致验证后无法完成回调。

解决步骤

1. 配置Azure应用注册的重定向URI

在Azure门户的应用注册页面:

  • 进入你的应用,选择身份验证选项卡
  • 添加重定向URI:本地测试可选择公共客户端(移动和桌面)类型,填入http://localhost:8000/redirect;如果是服务器端应用,选择Web类型填写对应服务地址
  • 保存配置

2. 切换到支持MFA的授权码流程

使用MSAL的授权码流程实现交互式登录,完成MFA验证后获取用户令牌。修改后的代码示例:

import msal
import webbrowser
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

# 配置参数
client_id = "你的客户端ID"
tenant_id = "你的租户ID"
authority = f"https://login.microsoftonline.com/{tenant_id}"
scopes = ["Chat.Read", "Chat.ReadWrite"]  # 直接指定所需权限,避免使用.default

# 初始化公共客户端应用(适配用户交互式登录场景)
app = msal.PublicClientApplication(client_id, authority=authority)

redirect_uri = "http://localhost:8000/redirect"
auth_code = None

# 临时HTTP服务,用于接收重定向返回的授权码
class AuthCallbackHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global auth_code
        if self.path.startswith("/redirect"):
            # 从回调URL中提取授权码
            auth_code = self.path.split("code=")[1].split("&")[0]
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(b"登录验证完成,可关闭此页面。")

# 启动临时服务线程
server = HTTPServer(("localhost", 8000), AuthCallbackHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()

# 生成授权URL并打开浏览器引导用户登录
auth_request_url = app.get_authorization_request_url(scopes, redirect_uri=redirect_uri)
webbrowser.open(auth_request_url)

# 等待用户完成MFA验证并返回授权码
while auth_code is None:
    pass

# 使用授权码交换访问令牌
token_result = app.acquire_token_by_authorization_code(
    auth_code,
    scopes=scopes,
    redirect_uri=redirect_uri
)

if "access_token" in token_result:
    access_token = token_result["access_token"]
    print("令牌获取成功:", access_token)
else:
    print("令牌获取失败:", token_result.get("error_description"))

3. 权限验证

确保你的应用注册中已添加Chat.Read和Chat.ReadWrite的委托权限,且管理员已完成租户级管理员同意(若需覆盖全租户用户),否则用户登录时需手动确认权限授权。

关键说明

  • 授权码流程是支持MFA的标准用户认证方式,适合需要以真实用户身份访问Teams群聊的场景
  • ROPC流程存在密码泄露风险,且不支持MFA,微软不推荐在生产环境使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:05:18