我需要限制对我的Spring Cloud Gateway的访问,只允许访问一组特定的客户端IP (基本上是为了有一个IP白名单)。我相信有一种简单的方法可以做到这一点,只需调优网关的yaml配置,并且不需要为这个简单的任务编写任何自定义筛选器代码。我该怎么做呢?
spring.cloud.gateway.security..。什么?
发布于 2019-07-04 17:47:16
您可以使用RemoteAddr路由谓词Factory.You可以找到有关如何设置和配置它的更多详细信息in the docs。
发布于 2020-01-28 20:33:34
您还可以使用GlobalFilter来限制访问。它会过滤所有请求,如果不是一个简单的远程地址限制,您可以将您的自定义逻辑放入过滤器中。
@Bean
@Order(-1)
public GlobalFilter whitelistFilter() {
return (exchange, chain) -> {
// TODO - init your whitelist
List<String> whitelist = new ArrayList<>();
whitelist.add("localhost");
// verify request remote address
String id = exchange.getRequest().getRemoteAddress().getHostName();
if (!whitelist.contains(id)) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
return chain.filter(exchange);
};
}发布于 2021-01-15 13:16:16
添加到@OlgaMaciaszek的答案中。下面是如何使用RemoteAddr谓词。..。(如果您想通过编程方式添加白名单中的if,而不是在yaml文件中进行硬编码)
List<String> whitelist = <your list of whitelisted Ips> ;
RemoteAddrRoutePredicateFactory predicateFactory = new RemoteAddrRoutePredicateFactory();
if (!predicateFactory.apply(predicateFactory.newConfig()
.setRemoteAddressResolver(XForwardedRemoteAddressResolver.maxTrustedIndex(2)).setSources(whitelist))
.test(exchange)) {
log.error("IP not whitelisted. Stopping futher communications.");
return GatewayResponseHelper.setIPNotWhiteListResponse(exchange);
}
log.info("IP is whitelisted. Proceeding with request.");
return chain.filter(exchange);
如果您的服务位于某个代理层之后,则可以使用XForwardedRemoteAddressResolver。或默认RemoteAddressResolver。通过类/文档了解更多内容。
https://stackoverflow.com/questions/56865409
复制相似问题