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

默认Cookie认证方案下GraphServiceClient报IDW10503的解决方法

问题原因

默认认证方案设为Cookie后,GraphServiceClient依赖的TokenAcquisition组件默认使用当前请求的Cookie认证方案,但Cookie方案没有对应的Azure AD配置,导致无法识别云实例,抛出IDW10503: Cannot determine the cloud Instance. The provided authentication scheme was ''异常。

解决方案

方案1:配置TokenAcquisition指定认证方案

在服务配置中明确指定TokenAcquisition使用OpenID Connect认证方案,确保GraphServiceClient能获取正确的Azure AD令牌:

var builder = WebApplication.CreateBuilder(args);

// 配置认证,默认方案为Cookie,同时注册OpenID Connect方案
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddNegotiate()
    .AddMicrosoftIdentityWebApp(builder.Configuration, configSectionName: "Authentication:AzureAD", 
        openIdConnectSchemeName: OpenIdConnectDefaults.AuthenticationScheme);

// 添加Graph服务并指定令牌获取的默认认证方案
builder.Services.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
    .AddTokenAcquisition(options =>
    {
        options.DefaultAuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddInMemoryTokenCaches();

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// 中间件配置(保持原有逻辑不变)
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();

app.Run();

方案2:注册Identity时直接关联Graph服务

在注册Microsoft Identity Web App时直接关联Graph服务,自动绑定正确的认证方案:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddNegotiate()
    .AddMicrosoftIdentityWebApp(builder.Configuration, "Authentication:AzureAD")
    // 启用下游API令牌获取并关联Graph服务
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
    .AddInMemoryTokenCaches();

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

// 后续中间件配置同上
必要配置验证

确保appsettings.json中包含完整的Azure AD和Graph配置(示例):

{
  "Authentication": {
    "AzureAD": {
      "Instance": "https://login.microsoftonline.com/",
      "Domain": "your-domain.onmicrosoft.com",
      "TenantId": "your-tenant-id",
      "ClientId": "your-client-id",
      "CallbackPath": "/signin-oidc"
    }
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "User.Read Mail.Read"
  }
}

页面代码无需修改,保持原有的[Authorize]特性和GraphServiceClient注入即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:48:32