December 6, 2018

Application Insights Trace MVC Authenticated User Info

I suppose every developer love application insights. Seamless integration with Visual Studio, powerful analytics dashboard and most important thing, acceptable price tier.

There is a lot of docs on how to integrate with Application Insights, but recently I get into the situation whereby I need record each request authenticated user to Application Insights. By default, if we don't supply these parameter, Application Insights will choose random character as your session ID and user Id.

Here is a code snippet that you can use if you want record your user Id, username, email or whatever you have in you MVC controller claims identity.

var requestTelemetry = telemetry as RequestTelemetry;

HttpContext currentContext = HttpContext.Current;
if (currentContext.User.Identity.IsAuthenticated)
{
     var identity = (ClaimsIdentity)currentContext.User.Identity;
     IEnumerable<Claim> claims = identity.Claims;
     var memberId = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
     var memberUsername = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;

     requestTelemetry.Context.User.Id = memberId;
     requestTelemetry.Context.User.AuthenticatedUserId = memberUsername;
}

In my case, claims identity consist both userID and username (as claim type name). When request telemetry initialized and current context is authenticated, user ID and username will be auto assign.

In order to make this work, you need initialize this part into startup file.

Dependency Injector for startup.cs
public void ConfigureServices(IServiceCollection services)
{
      // Use this if MyCustomTelemetryInitializer can be constructed without DI injected parameters
      services.AddSingleton<ITelemetryInitializer>(new RequestBodyInitializer());
}

Happy coding!