Application Insights User ID from ASP.NET Core identity

眉间皱痕 提交于 2020-02-23 06:17:28

问题


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);
}

回答1:


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.



来源:https://stackoverflow.com/questions/60244414/application-insights-user-id-from-asp-net-core-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!