Reputation: 1899
I need to restrict access to my Spring Cloud Gateway to a specific set of client IPs (basically to have a IP whitelist). I am sure there is a simple way to do it just but tuning the yaml configuration for the gateway and not needing any custom filter coding for that simple task. How can I do it?
spring.cloud.gateway.security... ?
Upvotes: 1
Views: 5614
Reputation: 3912
You can use the RemoteAddr Route Predicate Factory.You can find more details on how to set it up and configure it in the docs.
Upvotes: 4
Reputation: 11
adding to the answer of @OlgaMaciaszek. Here is how you can use RemoteAddr Predicate. . (if you want to programatically add the whitelisted Ips instead of hardcoding in yaml file)
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);
you can use XForwardedRemoteAddressResolver if your service is behind some proxy layer. or default RemoteAddressResolver. Go through the class/doc for more understanding.
Upvotes: 1
Reputation: 56
You can also use GlobalFilter to restrict access. It filters all requests and you can put your customized logic in the filter if it is not a simple remote address restrict.
@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);
};
}
Upvotes: 0