Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 825
Priyank Panchal Avatar asked Feb 16 '20 00:02

Priyank Panchal


People also ask

How do I get application Insights ID?

To get the Application ID: From your Application Insights resource, click API Access. Copy the Application ID and paste it to the Application Insights Application ID field of your bot's settings.

How do I find my user ID in net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How do you integrate application Insights in .NET core?

Open your project in Visual Studio. Go to Project > Add Application Insights Telemetry. Choose Azure Application Insights, then select Next. Choose your subscription and Application Insights instance (or create a new instance with Create new), then select Next.

What is Operation ID application Insights?

Application Insights defines a data model for distributed telemetry correlation. To associate telemetry with a logical operation, every telemetry item has a context field called operation_Id . This identifier is shared by every telemetry item in the distributed trace.


1 Answers

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.

like image 133
Priyank Panchal Avatar answered Oct 02 '22 23:10

Priyank Panchal