3

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Molloch
  • 2,261
  • 4
  • 29
  • 48

1 Answers1

2

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

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40