Web API 使用 Azure AD 授权属性返回 401 未授权守护程序应用程序

Web API Authorize Attribute with Azure AD returning 401 Unauthorized for daemon app

我正在关注 this guide 如何使用 Azure AD Auth 设置我的 ASP.NET Core Web API 以便被称为我的守护程序应用程序客户端。

我相信我已经根据指南设置了所有内容,但是当我获得令牌并调用我的 API 时,我仍然在控制器上收到 401 returned [Authorize] 属性。

我一定是漏掉了什么。这是相关代码:

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);

Web 清单API:

"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"
  }
],

我已将此应用程序角色授予守护程序应用程序: User assignment required? 设置为 No 对于 Web API。

我缺少什么才能成功 return?

您应该添加身份验证中间件 app.UseAuthentication(); :

app.UseAuthentication();
app.UseAuthorization();

这样 JWT Bearer 中间件将处理令牌验证并对用户进行身份验证。