prinkpan
prinkpan

Reputation: 2247

Application Insights User ID from ASP.NET Core identity

I am using .NET Core 3.1. I want to populate the User ID property in Application Insights with the ASP.NET Core identity username. I got this article by Microsoft, but it is for the full .NET Framework. I also tried the following code given here (I changed claim to Identity)

public class TelemetryEnrichment : TelemetryInitializerBase
{
    public TelemetryEnrichment(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
    {
    }

    protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
    {
        telemetry.Context.User.AuthenticatedUserId =
            platformContext.User?.Identity.Name ?? string.Empty;
    }
}

but don't know how to include it in the pipeline. I tried services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>(); but it doesn't help. Application Insights is still showing its own User ID.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, ApplicationRole>(
        options => { 
            options.Stores.MaxLengthForKeys = 128;
            options.User.RequireUniqueEmail = true;
            options.Password.RequiredLength = 8;
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders()
        .AddRoles<ApplicationRole>()
        .AddSignInManager<ApplicationSignInManager>();

    services.AddControllersWithViews()
        .AddNewtonsoftJson()
        .AddRazorRuntimeCompilation();

    services.AddRazorPages();

    services.AddMvc(mvcOptions =>
    {
        mvcOptions.ModelBinderProviders.Insert(0, new ModelBinderProvider());
    })
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "");
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

    services.AddAntiforgery(options => options.HeaderName = "XSRF-TOKEN");

    services.AddFlashMessage();

    services.AddSingleton<IEmailUtility, EmailUtility>();
    services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddApplicationInsightsTelemetry();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>();

    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    });
    var mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);
}

Upvotes: 12

Views: 5602

Answers (1)

prinkpan
prinkpan

Reputation: 2247

Answering my own question for completeness. The code given in the question works perfectly fine. I will just put it here again.

To get the ASP.NET Core identity username in your Application Insights, you need a custom telemetry initializer Please refer to original answer by @PeterBons here

public class TelemetryEnrichment : TelemetryInitializerBase
{
    public TelemetryEnrichment(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
    {
    }

    protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
    {
        telemetry.Context.User.AuthenticatedUserId =
            platformContext.User?.Identity.Name ?? string.Empty;
    }
}

Then you need to register it in your Startup.cs ConfigureServices as below:

public void ConfigureServices(IServiceCollection services)
{
    ...
    ...
    services.AddApplicationInsightsTelemetry();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<ITelemetryInitializer, TelemetryEnrichment>();
    ...
    ...
}

Remember to put AddApplicationInsightsTelemetry() above the AddSingleton()

Once this is set up, the identity username is displayed under Auth User ID property in Application Insights.

-- Update --

The identity username is now displayed under Auth Id instead of Auth User ID as stated above.

Upvotes: 23

Related Questions