Azure API管理策略将JWT令牌记录到App Insights(使用事件中心)



使用Azure APIM+JWT验证。我曾尝试记录JWT令牌的输出,但没有任何运气(理想情况下只是提取用户名(。请参阅下面的政策。通过EventHub传输JWT令牌后,如何将其记录到Application Insights中的customDimension?

政策:

<policies>
<inbound>
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" output-token-variable-name="jwt-token">
<openid-config url="https://OUR_IDP/.well-known/openid-configuration" />
</validate-jwt>
<set-header name="caller-objectid" exists-action="override">
<value>@(((Jwt)context.Variables["jwt-token"]).Subject)</value>
</set-header>
<set-variable name="message-id" value="@(Guid.NewGuid())" />
<!--context.Request.Headers.GetValueOrDefault("Authorization", "DEFAULT"),-->
<log-to-eventhub logger-id="LOGGER_ID_HERE" partition-id="0">@{
var requestLine = string.Format("{0} {1} HTTP/1.1rn",
context.Request.Method,
context.Request.Url.Path + context.Request.Url.QueryString);

var body = context.Request.Body?.As<string>(true);
if (body != null && body.Length > 1024)
{
body = body.Substring(0, 1024);
}

var headers = context.Request.Headers
.Where(h => h.Key != "Ocp-Apim-Subscription-Key")
.Select(h => string.Format("{0}: {1}", h.Key, String.Join(", ", h.Value)))
.ToArray<string>();

var headerString = (headers.Any()) ? string.Join("rn", headers) + "rn" : string.Empty;

return "request:"   + context.Variables["message-id"] + "n"
+ requestLine + headerString + "rn" + body;
}</log-to-eventhub>
</inbound>
<backend>
<forward-request follow-redirects="true" />
</backend>
<outbound>
<log-to-eventhub logger-id="LOGGER_ID_HERE" partition-id="0">@{
var statusLine = string.Format("HTTP/1.1 {0} {1}rn",
context.Response.StatusCode,
context.Response.StatusReason);

var body = context.Response.Body?.As<string>(true);
if (body != null && body.Length > 1024)
{
body = body.Substring(0, 1024);
}

var headers = context.Response.Headers
.Select(h => string.Format("{0}: {1}", h.Key, String.Join(", ", h.Value)))
.ToArray<string>();

var headerString = (headers.Any()) ? string.Join("rn", headers) + "rn" : string.Empty;

return "response:"  + context.Variables["message-id"] + "n"
+ statusLine + headerString + "rn" + body;
}</log-to-eventhub>
</outbound>
<on-error />
</policies>

我发现我可以在APIM的ApplicationInsights配置部分中添加请求头日志记录。这将正确记录标头。

最新更新