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

集成Microsoft Entra ID的.NET Core控制台调用Web API失败求助

问题:调用受Microsoft Entra ID保护的ASP.NET Core Web API时出现权限验证错误

1. ASP.NET Core Web API配置

我创建了一个ASP.NET Core Web API并在Microsoft Entra ID中完成注册,Program.cs中的配置如下:

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization();

2. 控制台客户端应用配置

随后在Entra ID中注册了另一个控制台应用,代码配置如下:

var app = ConfidentialClientApplicationBuilder
               .Create(appId)
               .WithClientSecret(appSecret)
               .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
               .Build();

var result = app.AcquireTokenForClient(new[] { $"api://{apiAppId}/.default" })
               .ExecuteAsync();

result.Wait();

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Result.AccessToken);

var response = client.GetAsync(endpointUrl);
response.Wait();

3. Entra ID已完成的配置操作

  • 在API应用的“公开API”设置中创建了名为xxx.read的范围
  • 将控制台客户端应用添加到API的授权客户端应用列表中
  • 控制台客户端已添加对应API权限

4. 调用时抛出的错误信息

Bearer was not authenticated. Failure message: IDW10201: Neither scope nor roles claim was found in the bearer token. Authentication scheme used: 'Bearer'.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: Bearer was not authenticated. Failure message: IDW10201: Neither scope nor roles claim was found in the bearer token. Authentication scheme used: 'Bearer'.
dbug: Microsoft.AspNetCore.Authorization.AuthorizationMiddleware[0]
Policy authentication schemes did not succeed
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware: Debug: Policy authentication schemes did not succeed
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Bearer was challenged.

5. 相关配置截图

  • API应用的“公开API”设置:
    API应用的“公开API”设置
  • 客户端应用的API权限:
    客户端应用的API权限

请问我哪里配置遗漏了?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:48:25