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

ASP.NET Core用Microsoft Identity调用Graph API遇IDW10503错误

解决IDW10503错误:调用Microsoft Graph API时指定正确的认证方案

问题根源

你的ASP.NET Core应用同时配置了Cookies和AzureAd两种认证方案,默认认证方案为Cookies。当调用Graph API时,TokenAcquisition服务默认使用当前的默认认证方案(Cookies),但Cookies方案未关联Azure AD的令牌缓存与身份信息,导致无法确定云实例,触发IDW10503错误。

解决方案

方案1:调用Graph API时显式指定认证方案

在控制器中注入ITokenAcquisition,手动获取AzureAd方案的访问令牌并附加到GraphClient请求中:

private readonly IGraphServiceClient _graphClient;
private readonly ITokenAcquisition _tokenAcquisition;
private readonly IConfiguration _configuration;

public YourController(IGraphServiceClient graphClient, ITokenAcquisition tokenAcquisition, IConfiguration configuration)
{
    _graphClient = graphClient;
    _tokenAcquisition = tokenAcquisition;
    _configuration = configuration;
}

public async Task<IActionResult> FetchEvents()
{
    var scopes = _configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ') ?? Array.Empty<string>();
    // 显式指定使用AzureAd认证方案获取令牌
    var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes, authenticationScheme: "AzureAd");
    
    // 为GraphClient设置Bearer令牌
    _graphClient.AuthenticationProvider = new DelegateAuthenticationProvider(request =>
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        return Task.CompletedTask;
    });
    
    var events = await _graphClient.Me.Events.Request().GetAsync();
    return View(events);
}

方案2:全局配置TokenAcquisition的默认认证方案

修改Startup.cs的认证配置,为TokenAcquisition设置默认使用AzureAd方案,避免每次调用都手动指定:

var authentication = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.LoginPath = "/LoginPage";
    options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
});

authentication
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), Microsoft.Identity.Web.Constants.AzureAd, null)
    .EnableTokenAcquisitionToCallDownstreamApi(Configuration.GetValue("DownstreamApi:Scopes")?.Split(' '))
    .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
    .AddInMemoryTokenCaches()
    // 添加TokenAcquisition选项,指定默认认证方案
    .AddTokenAcquisitionOptions(options =>
    {
        options.AuthenticationScheme = "AzureAd";
    });

方案3:为特定控制器/方法指定AzureAd认证

如果业务允许,可在需要调用Graph API的控制器或方法上强制使用AzureAd认证方案,TokenAcquisition会自动使用该方案获取令牌:

[Authorize(AuthenticationSchemes = "AzureAd")]
public async Task<IActionResult> FetchEvents()
{
    var events = await _graphClient.Me.Events.Request().GetAsync();
    return View(events);
}

验证要点

  • 确保AzureAd配置节中的Instance、ClientId、TenantId等参数正确
  • 确认应用已在Azure AD中授予所需的Graph API权限(如Calendars.Read)
  • 验证用户登录时已同意所需的权限范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:53:15