Search code examples
c#azureasp.net-coreauthenticationjwt

Do I actually need to configure JwtBearerOptions when using AddMicrosoftIdentityWebApi?


I would like to configure a Microsoft Entra ID protected ASP.Net Core 8.0 API according to the docs. The API will be called by daemon apps exclusively.

In Visual Studio 2022, I have created a new Asp.Net Core 8.0 Web API project, with authentication enabled, using Microsoft identity platform as authentication type.

In my default WeatherForecastController I got [Authorize(Roles = "MyApp.Read.All")], the same App role which I have configured in both the client and API App Registrations in Azure.

In my Program.cs I got

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

where appsettings.json seem to have the appropriate values for my tenant in the AzureAd object. For example Instance, TenantId etc.

With these default settings, do I actually need to validate the token with JwtBearerOptions I found here?


Solution

  • My question was regarding how I ensure validation of the specific token claims like aud. Is that taken care of in my existing config, or do I need to set JwtBearerOptions?

    Yes it will automatically validates specific token claims like aud (audience). your current configuration check that only authenticated requests with valid tokens can access your API. However, when you want to validate specific token claims like the aud (audience), you might need some additional configuration for that.

    By default, when you configure authentication using .AddMicrosoftIdentityWebApi, it sets up the JWT Bearer token middleware to validate several standard claims such as iss (issuer), aud (audience), nbf (not before), and exp (expiry), among others. This means the audience (aud) claim is checked to ensure it matches your API's identifier (the Application ID URI) by default. but for custom token validation you need to use JwtBearerOptions.

    Below is the sample code:

    builder.Services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"),
            jwtBearerOptions =>
            {
                //Custom validation for the audience
                jwtBearerOptions.TokenValidationParameters.ValidAudience = "your-audience-uri";
                jwtBearerOptions.TokenValidationParameters.NameClaimType = "preferred_username";
                jwtBearerOptions.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var claims = context.Principal.Claims;
                        var audience = claims.FirstOrDefault(c => c.Type == "aud")?.Value;
                        if (audience != "expected-audience-value")
                        {
                            context.Fail("Invalid audience");
                        }
    
                        return Task.CompletedTask;
                    }
                };
            });
    

    Here is the official document you could consider as reference which an guide you how to customize the handling of JWT tokens in your application:

    https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration#configure-jwt-bearer-middleware