【发布时间】:2020-07-25 04:46:24
【问题描述】:
我正在关注this guide,了解如何使用 Azure AD Auth 设置我的 ASP.NET Core Web API,以便将其称为我的守护程序应用程序客户端。
我相信我已经按照指南设置了所有内容,但是当我获得令牌并调用我的 API 时,我仍然会在具有 [Authorize] 属性的控制器上返回 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。
让这个成功返回我缺少什么?
【问题讨论】:
标签: c# asp.net-core azure-active-directory azure-api-apps