Log Authentication Events with Microsoft.Identity.Web in ASP.NET Core 6.0

Viewed 828

I'm trying to work out how to configure logging Authentication events that occur is MicrosoftIdentityWeb in ASP.NET Core 6.0 and I'm having trouble finding a simple example.

My code is currently the .net60 template code, I've tried to follow previous examples to add logging, but I can't get it to work correctly:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

IConfiguration opt = builder.Configuration.GetSection("AzureAd");

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    // Was: .AddMicrosoftIdentityWebApi(Configuration);
    .AddMicrosoftIdentityWebApi(options =>
    {
        // Handle Auth events and bind Configuration here somehow?
    });

...

How can I bind the configuration and subscribe to the authentication events so I can see why my authentication is failing and log auth attempts for security purposes?

1 Answers

The first step is to follow this blog post to add logging to your application.

Then you need to tweak the login levels like this:

.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("IdentityServer4", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.DataProtection", LogEventLevel.Debug)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.AspNetCore.Authorization", LogEventLevel.Information);

See the source code sample here for more details:

If this is not enough, you can get even more details by using the System.Diagnostics.Tracing sub-system that on Windows will send data to Event Tracing for Windows (ETW).

Related