【问题标题】:Web API Authorize Attribute with Azure AD returning 401 Unauthorized for daemon app带有 Azure AD 的 Web API 授权属性返回 401 Unauthorized for daemon app
【发布时间】: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


    【解决方案1】:

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

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

    这样 JWT Bearer 中间件将处理令牌验证和验证用户。

    【讨论】:

    • 你是救生员。我一定在某个地方的文档中错过了这一点。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2020-01-01
    • 1970-01-01
    • 2019-08-10
    • 2016-12-04
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多