Search code examples
c#asp.net-coreazure-active-directoryazure-api-apps

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


I am following this guide on how to set up my ASP.NET Core Web API with Azure AD Auth for being called my a daemon app client.

I believe I've setup everything according to the guide, but when I get the token and call my API, I am still getting 401 returned on a Controller with the [Authorize] attribute.

I must be missing something. Here is the relevant code:

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
{
...
}

Client code to get the token:

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

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

I have granted the daemon app this app Role: enter image description here User assignment required? is set to No For the Web API.

What am I missing to get this to return successfully?


Solution

  • You should add authentication middleware app.UseAuthentication(); :

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

    So that the JWT Bearer middleware will handle token validation and authenticate user .