How to configure Application Insights in Blazor Server app to include authenticated user in traces?

Viewed 339

When I follow the application insights docs for ASP.NET, the traces produced by Logger.Log() in Blazor components are logged in Application Insights, but the are not associated with logged in user.

It's probably because of SignalR nature.

How to configure Application Insights in Blazor Server app to include authenticated user in traces?

What I tried

I've added TelemetryInitializer

services.AddSingleton<ITelemetryInitializer, UserTelemetryInitializer>();

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

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

but any logs coming from Blazor are not associated with the User:

app insights logs

My asp.net core 6 app deployed to "On premise ISS" have app insights configured as follows:

services.AddApplicationInsightsTelemetry(options => 
    options.ConnectionString = Configuration.GetValue<string>("APPINSIGHTS_CONNECTIONSTRING"));

and a cookie authentication - authenticated user is always required in the blazor hub

services.Configure<IISServerOptions>(options => options.AutomaticAuthentication = false);

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie()

....

app.UseAuthentication();
app.UseAuthorization();


app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapRazorPages().RequireAuthorization();
    endpoints.MapBlazorHub().RequireAuthorization();
    endpoints.MapFallbackToPage("/_Host");
});

However, in the app insights portal I don't see any user id associated with the traces, requests or exception datasets.

Why is the user_Id missing in the logs?

0 Answers
Related