聊聊spring cloud gateway的XForwardedHeadersFilter

本文主要研究spring cloud gateway的XForwardedHeadersFilter

GatewayAutoConfiguration

spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java

@Configuration
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore(HttpHandlerAutoConfiguration.class)
@AutoConfigureAfter({GatewayLoadBalancerClientAutoConfiguration.class, GatewayClassPathWarningAutoConfiguration.class})
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {
    //......
    @Bean
    @ConditionalOnProperty(name = "spring.cloud.gateway.x-forwarded.enabled", matchIfMissing = true)
    public XForwardedHeadersFilter xForwardedHeadersFilter() {
        return new XForwardedHeadersFilter();
    }
    //......
}
默认注册了XForwardedHeadersFilter

XForwardedHeadersFilter

spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/filter/headers/XForwardedHeadersFilter.java

@ConfigurationProperties("spring.cloud.gateway.x-forwarded")
public class XForwardedHeadersFilter implements HttpHeadersFilter, Ordered {
    //......
    @Override
    public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders original = input;
        HttpHeaders updated = new HttpHeaders();

        original.entrySet().stream()
                .forEach(entry -> updated.addAll(entry.getKey(), entry.getValue()));

        if (isForEnabled()) {
            String remoteAddr = request.getRemoteAddress().getAddress().getHostAddress();
            List<String> xforwarded = original.get(X_FORWARDED_FOR_HEADER);
            // prevent duplicates
            if (remoteAddr != null &&
                    (xforwarded == null || !xforwarded.contains(remoteAddr))) {
                write(updated, X_FORWARDED_FOR_HEADER, remoteAddr, isForAppend());
            }
        }

        String proto = request.getURI().getScheme();
        if (isProtoEnabled()) {
            write(updated, X_FORWARDED_PROTO_HEADER, proto, isProtoAppend());
        }

        if (isPortEnabled()) {
            String port = String.valueOf(request.getURI().getPort());
            if (request.getURI().getPort() < 0) {
                port = String.valueOf(getDefaultPort(proto));
            }
            write(updated, X_FORWARDED_PORT_HEADER, port, isPortAppend());
        }

        if (isHostEnabled()) {
            String host = toHostHeader(request);
            write(updated, X_FORWARDED_HOST_HEADER, host, isHostAppend());
        }

        return updated;
    }

    //......
}
  • 如果spring.cloud.gateway.x-forwarded.for-enabled为true,则会写入X-Forwarded-For
  • 如果spring.cloud.gateway.x-forwarded.proto-enabled为true,则会写入X-Forwarded-Proto
  • 如果spring.cloud.gateway.x-forwarded.port-enabled为true,则会写入X-Forwarded-Port
  • 如果spring.cloud.gateway.x-forwarded.host-enabled为true,则会写入X-Forwarded-Host

每个enable属性都有一个append属性,用来决定是否是添加还是追加

    private void write(HttpHeaders headers, String name, String value, boolean append) {
        if (append) {
            headers.add(name, value);
            // these headers should be treated as a single comma separated header
            List<String> values = headers.get(name);
            String delimitedValue = StringUtils.collectionToCommaDelimitedString(values);
            headers.set(name, delimitedValue);
        } else {
            headers.set(name, value);
        }
    }
如果是append,则逗号分隔写入headers,如果不是则是采取set操作。

配置

    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.enabled",
      "description": "If the XForwardedHeadersFilter is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.for-append",
      "description": "If appending X-Forwarded-For as a list is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.for-enabled",
      "description": "If X-Forwarded-For is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.host-append",
      "description": "If appending X-Forwarded-Host as a list is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.host-enabled",
      "description": "If X-Forwarded-Host is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": 0,
      "name": "spring.cloud.gateway.x-forwarded.order",
      "description": "The order of the XForwardedHeadersFilter.",
      "type": "java.lang.Integer"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.port-append",
      "description": "If appending X-Forwarded-Port as a list is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.port-enabled",
      "description": "If X-Forwarded-Port is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.proto-append",
      "description": "If appending X-Forwarded-Proto as a list is enabled.",
      "type": "java.lang.Boolean"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.XForwardedHeadersFilter",
      "defaultValue": true,
      "name": "spring.cloud.gateway.x-forwarded.proto-enabled",
      "description": "If X-Forwarded-Proto is enabled.",
      "type": "java.lang.Boolean"
    }

小结

spring cloud gateway提供了XForwardedHeadersFilter,用来决定进行路由转发的时候转发哪些X-Forwarded相关的header,同时提供append选项,用来控制是否是追加还是覆盖到header中。

doc


code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.8k 声望
2k 粉丝
0 条评论
推荐阅读
2022年终总结
最近两年开始陷入颓废中,博客也写的越来越少了。究其原因,主要还是陷入了职业倦怠期,最近一次跳槽感觉颇为失败,但是碍于给的薪资高,为了五斗米折腰,又加上最近行情不好,想要往外跳也跳不了,就这样子一直...

codecraft阅读 724

feign调用把CPU吃满了?这个锅HttpMessageConverters来背
SpringEncoder / SpringDecoder 在每次编码 / 解码时都会调用 ObjectFactory&lt;HttpMessageConverters&gt;.getObject()).getConverters() 获取 HttpMessageConverters。

开翻挖掘机1阅读 474

Spring Cloud中MyBatis-Plus动态数据源刷新问题
在使用MyBatis-Plus的DynamicRoutingDataSource时遇到的问题,当我在配置中心动态增加或者删除了一个数据源,他并不会自动同步最新的数据源,导致我用DynamicDataSourceContextHolder.push(ds)方法的时候拿不到刚...

Pursuer丶阅读 690

封面图
这些不知道,别说你熟悉 Nacos,深度源码解析!
大家好,这篇文章跟大家聊下 SpringCloudAlibaba 中的微服务组件 Nacos。Nacos 既能做注册中心,又能做配置中心,这篇文章主要来聊下做配置中心时 client 端的一些设计,主要从源码层面进行分析,相信看完这篇文...

yanhom1阅读 299

封面图
【Spring Cloud】Feign调用异常触发降级后如何捕获异常
在Spring Cloud的微服务架构中,通常微服务之间通过feign/openfeign来进行http调用,并且启用hystrix并配置降级策略fallback,可以在http调用异常时触发降级,代码如下

kamier阅读 546

Spring Cloud OpenFeign调用流程
上一节给大家分享了Spring Cloud OpenFeign的启动流程,接下来给大家分享一下调用流程。话不多说,咱们直接开始。视频:[链接]调用流程xxxFeignClient → feign.ReflectiveFeign.FeignInvocationHandler#invoke→ f...

冯文议阅读 543

封面图
Nacos 中的配置文件如何实现加密传输
小伙伴们知道,Spring Cloud Config 很早就提供了配置文件的加解密功能,并且支持对称加密和非对称加密两种不同的模式。Nacos 作为分布式配置中心+服务注册中心的合体,在配置文件加密这块一直差点意思,不过好在...

Java架构师阅读 359

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.8k 声望
2k 粉丝
宣传栏