SpringCloud Gateway网关配置中,需要对访问的IP设置白名单,SpringCloud Gateway官方给出YML配置文件配置。
如下:
5.10. The RemoteAddr Route Predicate Factory
The RemoteAddr route predicate factory takes a list (min size 1) of sources, which are CIDR-notation (IPv4 or IPv6) strings, such as 192.168.0.1/16 (where 192.168.0.1 is an IP address and 16 is a subnet mask). The following example configures a RemoteAddr route predicate:
Example 10. application.yml
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: https://example.org
predicates:
- RemoteAddr=192.168.1.1/24
此处也支持多个不同网段的IP配置,多个IP用逗号分隔。如下:
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: https://example.org
predicates:
- RemoteAddr=192.168.1.1,172.19.2.181,168.10.11.3
针对SpringCloud Gateway 网关在代理服务后面的情况,如果不做特殊配置,那么访问的IP将是代理服务的IP,这种情况不是我们希望看到的。SpringCloud Gateway 官方给出方案,自定义获取remote address的处理器RemoteAddressResolver。官方配置如下:
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
.maxTrustedIndex(1);
...
.route("direct-route",
r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
.uri("https://downstream1")
.route("proxied-route",
r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
.uri("https://downstream2")
)
下面给出完整的Java配置文件:
package com.jc.gateway;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.gateway.support.ipresolver.RemoteAddressResolver;
import org.springframework.cloud.gateway.support.ipresolver.XForwardedRemoteAddressResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @ClassName: GatewayConfig
* @Author: jc
* @Date: 2020/6/17 18:18
* @Description:
*/
@Component
public class GatewayConfig {
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver.maxTrustedIndex(1);
//访问IP白名单
private static final String [] whitAddress={
"10.2.10.108","172.10.1.12", "192.18.9.31"
};
/**
* 通过设置自定义RemoteAddressResolver来自定义解析远程地址的方式,
* 来解决Spring Cloud Gateway位于代理层后面,可能与实际客户端IP地址不匹配的问题
*/
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("service-data",
r -> r.path("/service-data/**").and().remoteAddr(resolver,whitAddress)
.filters(f-> f.stripPrefix(1)).uri("lb://service-data"))
.build();
}
}
需要注意的是,YML文件配置,和JAVA代码配置可以同时生效,但是同一个routes 的ID 对应的路由服务只能有一个生效,即YML文件配置的优先级大于JAVA代码配置的优先级。
至此配置完成。
参考资料:
https://cloud.spring.io/spring-cloud-gateway/reference/html/