集成Microsoft Entra ID的.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权限:

请问我哪里配置遗漏了?
内容的提问来源于stack exchange,提问作者Jana

