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

从Azure B2C租户提取登录用户邮箱时的MS Graph API认证错误排查

问题描述

我正在构建一个托管在Azure上的Python Flask Web应用,功能包括:

  • 将图片存储到Blob存储
  • 将图片相关信息存储到Azure Database for PostgreSQL灵活服务器
  • 用户通过B2C用户流完成注册/登录,用户信息保存在B2C租户的用户选项卡中

我的需求是:从B2C租户获取用户邮箱,将其与Blob中图片的其他相关信息一同存入数据库的user_email字段。

尝试的实现代码

我用MS Graph API尝试实现,代码如下:

msal_authority = f"https://login.microsoftonline.com/{tenant_id}"

msal_scope = ["https://graph.microsoft.com/.default"]

msal_app = ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=msal_authority,
)

result = msal_app.acquire_token_silent(
    scopes=msal_scope,
    account=None,
)

if not result:
    result = msal_app.acquire_token_for_client(scopes=msal_scope)

if "access_token" in result:
    access_token = result["access_token"]
else:
    raise Exception("No Access Token found")

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json",
}

response = requests.get(
    url="https://graph.microsoft.com/v1.0/users",
    headers=headers,
)

app.logger.debug(json.dumps(response.json(), indent=4))

遇到的错误

ClientAuthenticationError: the current credential is not configured to acquire tokens from tenant: 12345678910"

说明:错误中的租户ID“12345678910”是B2C租户所在的主目录ID,而非B2C租户ID。我代码里的tenant_id已经设置为B2C租户ID,同时配置了对应的client_id和client_secret。

疑问

  1. 这种尝试从主目录获取令牌的情况是否正常?
  2. 用户登录B2C租户后,认证层面是否无需再与主目录交互?
  3. 是否需要配置以允许B2C租户从主目录获取令牌,还是我误用了Graph API,实际对接的是主目录而非B2C目录?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:50:10