我正在跟踪this guide,以了解如何使用Azure AD Auth设置我的ASP.NET Core Web API,从而将其称为守护程序应用程序客户端。
我相信我已经按照指南进行了所有设置,但是当我获得令牌并调用我的API时,我仍然在带有[Authorize]
属性的Controller上返回401。
我一定很想念东西。以下是相关代码:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services
.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
options.TokenValidationParameters.ValidAudiences = new[]
{
options.Audience, // my-api-client-id-guid
Configuration["AadAudienceUrl"], // https://myapi.azurewebsites.net
};
}
...
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAuthorization();
...
}
appsettings.json
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "my-api-client-id-guide",
"TenantId": "my-tenant-id-guid"
},
MyController.cs
[Authorize] // No role checks yet, just want to get basic auth working first
[ApiController]
[Route("mycontroller")]
public class MyController : ControllerBase
{
...
}
获取令牌的客户端代码:
AuthenticationContext ac = new AuthenticationContext(
authority: "https://login.microsoftonline.com/my-tenant-id-guid",
validateAuthority: true);
AuthenticationResult ar = await ac.AcquireTokenAsync(
"my-api-client-id-guid",
// "https://myapi.azurewebsites.net", // Both of these return a token successfully, but return 401 when used
new ClientCredential("my-daemon-app-client-id-guid", "daemon-app-secret"));
var token = new AuthenticationHeaderValue(ar.AccessTokenType, ar.AccessToken);
WebAPI清单:
"appRoles": [
{
"allowedMemberTypes": [
"Application"
],
"description": "Allow the application to access the service",
"displayName": "Application Access",
"id": "my-access-guid",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "ApplicationAccess"
}
],
我已授予守护程序此应用程序此角色:
对于Web API,User assignment required?
设置为No
。
要让它成功返回,我缺少什么?
答案 0 :(得分:1)
您应该添加身份验证中间件app.UseAuthentication();
:
app.UseAuthentication();
app.UseAuthorization();
JWT Bearer中间件将处理令牌验证并验证用户身份。