10

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);
}
prinkpan
  • 2,117
  • 1
  • 19
  • 32
  • Please make sure you add your custom initializers *after* calling `services.AddApplicationInsightsTelemetry();`. Can you post your complete service registration code? – Peter Bons Feb 17 '20 at 10:19
  • Thank you for your comment, @PeterBons. I have updated my question with the service registration code. – prinkpan Feb 17 '20 at 11:24
  • 1
    This is solved, I just realized that this comes up under `Auth User ID` in Application Insights. I was looking at `User ID`. Thank you. – prinkpan Feb 17 '20 at 11:37
  • 1
    I'm glad you figured out your issue. Would you please consider posting your solution as an answer? It makes it easier for other people having the same problem to discover the solution. – PerfectlyPanda Feb 17 '20 at 20:58

1 Answers1

21

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.

prinkpan
  • 2,117
  • 1
  • 19
  • 32
  • Priyank - some how above code does not work for me . I can see new Telemetry records/items but cant find properties added by me and assigned to authenticated id. I also clicked on the showall button but my custom properties or Auth id does not show up – Jack Sp Oct 29 '21 at 23:48
  • @JackSp, I believe it would be best if you can create a new post with the issue that you are facing. – prinkpan Nov 15 '21 at 08:41
  • This works thanks :) – SmallWorld Jul 11 '23 at 10:35