Skip to content

A Serilog enricher that enriches the log event with claims from Azure v1 and v2 accesstokens.

License

Notifications You must be signed in to change notification settings

intility/serilog-enrichers-azureclaims

Repository files navigation

Serilog.Enrichers.AzureClaims

Enriches Serilog events with information from the ClaimsPrincipal.

Build_and_Test Publish codecov

Nuget Nuget

Install the Serilog.Enrichers.AzureClaims NuGet package

Install-Package Serilog.Enrichers.AzureClaims

Then, apply the enricher to your LoggerConfiguration:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithUpn()
    .Enrich.WithDisplayName()
    .Enrich.WithTenantId()
    .Enrich.WithObjectId()
    .Enrich.WithAppId()
    // ...other configuration...
    .CreateLogger();

Included enrichers

The package includes:

  • WithUpn() - adds UserPrincipalName based on the ClaimType http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn
  • WithDisplayName() - adds DisplayName based on the ClaimType http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name or name or preferred_username
  • WithTenantId() - adds TenantId based on the ClaimType http://schemas.microsoft.com/identity/claims/tenantid or tid
  • WithObjectId() - adds ObjectId based on the ClaimType http://schemas.microsoft.com/identity/claims/objectidentifier or oid
  • WithAppId - adds AppId based on the CLaimType appid or azp

Installing into an ASP.NET Core Web Application

You need to register the IHttpContextAccessor singleton so the enrichers have access to the requests HttpContext to extract the data. This is what your Program class should contain in order for this enricher to work as expected:

// ...
using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.AddSerilog(new LoggerConfiguration()
    .Enrich.WithUpn()
    .Enrich.WithDisplayName()
    .Enrich.WithTenantId()
    .Enrich.WithObjectId()
    .Enrich.WithAppId()
    .CreateLogger());

// ...
builder.Services.AddHttpContextAccessor();
// ...

var app = builder.Build();
app.UseSerilogRequestLogging();
// ...