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

如何在C# OpenIdConnect与Microsoft Graph间共享用户认证上下文

问题背景

我们有一个C# WebForms网站,采用以下代码实现Azure AD用户认证:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
    ClientId = clientId,
    Authority = authority, // aadInstance + tenant,本质是一个URL
    Scope = OpenIdConnectScope.OpenIdProfile,
    ResponseType = OpenIdConnectResponseType.IdToken,
    // 下方还定义了TokenValidationParameters和Notifications...
}

用户登录后,通过以下代码获取token:

HttpContext.Current.GetOwinContext().Authentication.AuthenticateAsync("Cookies")
    .GetAwaiter().GetResult().Properties.Dictionary["id_token"];

将此id_token作为Authentication请求头调用Microsoft Graph API时,收到错误:

Access token validation failure. Invalid audience.

已知该问题是因为id_token的受众并非Microsoft Graph API,而是我们自身的应用。

需求

修改UseOpenIdConnectAuthentication的调用方式,获取可复用的认证凭证,以登录用户的权限上下文访问Microsoft Graph API。需要提供C#实现方案,从用户会话生成可用于Graph API的认证信息。

已尝试方案
  • 参考相关方案修改responseType和scope以获取access_token:设置为OpenIdConnectResponseType.CodeIdTokenToken,通过GetResult().Properties.Dictionary["access_token"]获取,但触发错误:

    AADSTS70005: The application requested an unsupported response type '' when requesting a token.

  • 尝试设置responseType为OpenIdConnectResponseType.CodeIdToken时,网站可正常运行,但生成的access_token调用Graph仍报“Invalid audience”错误。
  • 将OpenIdConnectAuthenticationOptions的SaveToken、RedeemCode设为True,添加resource为client_id,仅保证网站正常运行,未解决Graph API的报错问题。
  • 尝试使用客户端密钥调用Azure AD的token端点认证Graph API,虽能成功但无法获取用户上下文。
  • 已在Azure应用注册中添加委托权限,确保能返回access token和id token,但无效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:23:34