Spread the love

Authentication example:

public static void AzureADBearerAuthenticationExtension(this WebApplicationBuilder builder, JwtBearerOptions options)
{
    var azureAdOptions = builder.Configuration
                            .GetSection(key: nameof(AzureADOptions))
                            .Get<AzureADOptions>();

    string authority = $"https://{azureAdOptions.Domain}.b2clogin.com/{azureAdOptions.Domain}.onmicrosoft.com/{azureAdOptions.LoginFlowName}/v2.0/";

    IConfigurationManager<OpenIdConnectConfiguration> configurationManager =
        new ConfigurationManager<OpenIdConnectConfiguration>($"{authority}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());


    options.ConfigurationManager = configurationManager;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidAudience = azureAdOptions.Applications.Web.Id,
        ValidateIssuer = true,
        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        ConfigurationManager = (BaseConfigurationManager)configurationManager,
    };

    options.EventsType = typeof(MyJwtEventsHandler);
}

Where AzureAdOptions contains the configuration of your Azure AD.

MyJwtEventsHandler is the implementation of JwtEventsHandler. e.g.

 public class MyJwtEventsHandler(ILogger logger) : JwtBearerEvents
 {
     private readonly ILogger _logger = logger;
     public override Task AuthenticationFailed(AuthenticationFailedContext context)
     {
         // do something
         return base.AuthenticationFailed(context);
     }
 }

Register authentication:

 builder.Services.AddAuthentication(opt =>
 {
     opt.DefaultScheme = null;
 })
 .AddJwtBearer(AuthenticationSchemes.JwtBearer, options =>
 {
     builder.AzureADBearerAuthenticationExtension(options);
 });

 builder.Services.AddScoped<MyJwtEventsHandler>();
 builder.Services.AddSingleton<IAuthorizationMiddlewareResultHandler, MyAuthorizationMiddlewareResultHandler>();

MyAuthorizationMiddlewareResultHandler is the middleware behaviour overrider. Check Microsoft docs for more details.

Use on your controller:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Cheers and Peace out!!!