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

如何为envoy.filters.http.jwt_authn配置JWT校验失败的自定义状态码

可行的实现方案有两种,分别适配不同的Envoy版本场景:


方案1:使用HTTP连接管理器自定义响应映射(推荐,适配Envoy v1.21及以上版本)

该方案无需额外编写逻辑,仅通过原生配置即可实现状态码替换:

  • envoy.filters.http.jwt_authn校验JWT失败时,会自动在响应头添加x-envoy-auth-failure-reason: jwt_authn标识,同时返回默认401状态码
  • 在HTTP连接管理器的配置中添加custom_response_mappers规则,匹配状态码=401且x-envoy-auth-failure-reason=jwt_authn的响应,将状态码替换为指定的443即可

配置示例参考:

http_filters:
- name: envoy.filters.http.jwt_authn
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
    # 原有JWT校验配置保持不变
- name: envoy.filters.http.router
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
custom_response_mappers:
- filter:
    and_filter:
      filters:
      - status_code_filter:
          comparison:
            op: EQ
            value: 401
      - header_filter:
          header:
            name: x-envoy-auth-failure-reason
            exact_match: jwt_authn
  status_code: 443
  # 若需要同时修改响应体可添加body字段配置

方案2:使用Lua过滤器拦截修改(适配v1.21以下旧版本Envoy)

如果使用的Envoy版本不支持自定义响应映射,可通过插入Lua过滤器实现逻辑:

  • 在envoy.filters.http.jwt_authn过滤器之后、路由过滤器之前插入envoy.filters.http.lua过滤器
  • 编写Lua逻辑拦截响应,匹配JWT校验失败的特征后修改状态码即可

配置示例参考:

http_filters:
- name: envoy.filters.http.jwt_authn
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
    # 原有JWT校验配置保持不变
- name: envoy.filters.http.lua
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
    inline_code: |
      function envoy_on_response(response_handle)
        local headers = response_handle:headers()
        if headers:get(":status") == "401" and headers:get("x-envoy-auth-failure-reason") == "jwt_authn" then
          headers:replace(":status", "443")
        end
      end
- name: envoy.filters.http.router
  typed_config:
    "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

注意事项

  • 443属于非标准HTTP状态码,需要确认全链路代理、客户端都支持非标准状态码的透传和识别,避免被中间节点自动覆盖为其他标准状态码
  • 若需要进一步区分JWT校验失败的具体原因,可同时在自定义响应中添加专属响应头或者修改响应体内容,降低客户端识别成本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:54:00