遥测和身份验证

Telemetry and Authentication

我在我的网络 api 项目中使用了 AuthenticationHandler。它检查 api 键。我想在用户通过身份验证时使用 Application Insigth 发送事件。

我尝试执行 ITelemetryInitializer,但是当我尝试执行请求时,TelemetryInitializer 在 AuthenticatedHandler 之前被调用,因此未通过身份验证...

如何将遥测与身份验证一起使用?我是否需要在 AuthenticationHandler 中获取遥测服务并发送事件? ITelemetryInitializer 是好方法吗?但是为什么在认证之前调用ITelemetryInitializer?

我不是很清楚

从您的用例来看,遥测初始化程序似乎并不理想。例如,如果您想向所有请求添加内容,它们很有用。比如版本号之类的。

如果我没记错的话,您仍然可以在初始化程序中检查请求并检查请求是否经过身份验证,但这没有多大意义,恕我直言。另外,对于“订单”问题,这里是文档的一部分:

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.

所以,我要做的是将 TelemetryClient 注入到您的 AuthenticationHandler 中,并根据您的需要在其中检测代码。可以发送很多情况,比如 API 密钥是否无效,或者相同的 API 密钥被使用了多少次。请注意您发送的内容不要包含个人身份信息 (PII)。

就像我在评论中发布的那样,这里是使用 TelemetryClient 通过构造函数注入 https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#how-can-i-track-telemetry-thats-not-automatically-collected 发送自定义遥测数据的示例。