Flo
Flo

Reputation: 83

Telemetry and Authentication

I used a AuthenticationHandler in my web api project. It checkes a api key. I want to send the event with Application Insigth when the user is authenticated.

I tried to do a ITelemetryInitializer but when I try to do a request, the TelemetryInitializer is called before the AuthenticatedHandler so is not authenticated...

How I could use telemetry with the authentication ? Have I need to get the telemetry's service in my AuthenticationHandler and send the event ? Is a ITelemetryInitializer is good way ? But why the ITelemetryInitializer is called before the authentication ?

It's very not clear for me.

Upvotes: 0

Views: 449

Answers (1)

jpgrassi
jpgrassi

Reputation: 5732

Seems that from your use case, telemetry initializers are not ideal. They are useful if you want to, for example, add things to all requests. Like a version number or the like.

If I'm not mistaken, you can still check the request inside the initializer and check if the request is authenticated, but that doesn't make much sense, IMHO. Also, for the "order" question, here is a portion of the docs:

If you provide a telemetry initializer, it's called whenever any of the Track*() methods are called. This includes Track() methods called by the standard telemetry modules.

So, what I would do is inject the TelemetryClient inside your AuthenticationHandler, and instrument the code there as you see fit. Could send many cases, like if the API key is invalid, or how many times the same API key was used. Just be careful to what you send to not include personally identifiable information (PII).

Like I posted in the comments, here is an example of using the TelemetryClient via constructor injection https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#how-can-i-track-telemetry-thats-not-automatically-collected to send custom telemetry.

Upvotes: 1

Related Questions