'JwtBearerOptions Configure method not getting executed

I have asp.net core 3.1 web api project with the following code :

Startup.cs

public virtual void ConfigureServices(IServiceCollection services) =>
    services
    .AddFrameworkServices()
    .AddApplicationInsights(this.configuration)
    .AddResponseCompression()
    .AddCustomConfigureOptions();

CustomServiceCollectionExtensions.cs

public static IServiceCollection AddCustomConfigureOptions(this IServiceCollection services) =>
  services
    .ConfigureOptions<ConfigureAuthenticationOptions>();
    .ConfigureOptions<ConfigureJwtBearerOptions>();

ConfigureAuthenticationOptions.cs

public class ConfigureAuthenticationOptions : IConfigureOptions<AuthenticationOptions>
{
   public void Configure(AuthenticationOptions options) =>
      options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}

ConfigureJwtBearerOptions

public class ConfigureJwtBearerOptions : IConfigureOptions<JwtBearerOptions>
{
    private readonly IConfiguration configuration;
    public ConfigureJwtBearerOptions(IConfiguration configuration) => this.configuration = configuration;
    public void Configure(JwtBearerOptions options)
    {
        options.Authority = configuration[C.AppKeys.AADInstance] + configuration[C.AppKeys.AADTenantID];
        options.Audience = configuration[C.AppKeys.AADAudience];
    }
}

On debugging I found that Configure method of ConfigureJwtBearerOptions.cs file is not getting triggered

Can anyone help me with their guidance to fix this issue



Solution 1:[1]

I have been researching .NET authentication and Authorization and found that over the last year this landscape seemed to evolve pretty rapidly.

In the latestest documentationn I found Microsoft recommends different auth libraries for different auth types here: https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-v2-libraries

In our latest .net 6 web API's are using Microsoft.Identity.Web and using services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(azureConfiguration, "AzureAd"); to add our authentication. We previously used .AddAuthentication().AddJwtBearer(options => {...})

I am currently learning this new auth library myself here: https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration#customizing-token-validation

Hope this was helpful!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris - Haddox Technologies