You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure API Management:从JWT声明中提取appid并写入跟踪日志

Azure API Management 入站策略实现指引

核心实现步骤

  • 提取JWT中的appid声明:validate-jwt策略验证成功后,APIM会自动将JWT的所有声明加载到context.User.Claims集合中,通过表达式可直接提取目标声明值。
  • 写入跟踪日志:使用trace策略将提取到的appid输出到APIM跟踪日志,用于调试和监控。
  • 添加自定义请求头(后续扩展):通过set-header策略将appid注入新请求头,随请求转发给后端服务。

修改后的完整策略配置

<policies>
    <!-- Throttle, authorize, validate, cache, or transform the requests -->
    <inbound>
        <base />
        <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Invalid or no JWT">
            <openid-config url="https://login.microsoftonline.com/{{MY_ID}}/v2.0/.well-known/openid-configuration" />
            <audiences>
                <audience>api://{{MY_API_ID}}</audience>
            </audiences>
            <issuers>
                <issuer>https://sts.windows.net/{{MY_ID}}/</issuer>
            </issuers>
        </validate-jwt>
        <!-- 提取appid并写入跟踪日志 -->
        <trace source="JWT-AppID-Extractor" severity="information">
            <message>Extracted appid from JWT: @(context.User.Claims.FirstOrDefault(c => c.Type == "appid")?.Value ?? "Not found")</message>
        </trace>
        <!-- 可选:添加自定义请求头转发给后端 -->
        <set-header name="X-Client-AppID" exists-action="override">
            <value>@(context.User.Claims.FirstOrDefault(c => c.Type == "appid")?.Value ?? "")</value>
        </set-header>
        <set-backend-service backend-id="backend1" />
    </inbound>
    <!-- Control if and how the requests are forwarded to services  -->
    <backend>
        <base />
    </backend>
    <!-- Customize the responses -->
    <outbound>
        <base />
    </outbound>
    <!-- Handle exceptions and customize error responses  -->
    <on-error>
        <base />
    </on-error>
</policies>

关键细节说明

  • 声明键匹配:若你的JWT中appid对应的声明键是azp(Azure AD v2版本令牌常见),只需将表达式中的"appid"替换为"azp"。
  • 空值容错:表达式中用??运算符处理appid不存在的情况,避免策略执行报错。
  • 日志级别调整:trace策略的severity可按需改为error、warning或information。
  • 请求头行为控制:set-header的exists-action设为override会覆盖同名现有头,若需保留原头可改为append。

内容的提问来源于stack exchange,提问作者dunkyduncs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:42:33