Home > Spring > Spring WebFlux > Get Client Remote Address from ServerExchange in Spring WebFlux and whitelist IP

Get Client Remote Address from ServerExchange in Spring WebFlux and whitelist IP

Below is the Spring WebFlux code to fetch the client Remote Address from the ServerExchange object. Say, we have a scenario wherein we have to check if the API request is coming from the authorized IP address list, in the web filter we will fetch the IP address of the client and will match with the set of given IP’s or CIDR notation to check if the IP is allowed or not. Based on the response we will decide whether to allow the user to access the endpoint or throw an Unauthorized exception.

ArrayList<String> whiteListIp = new ArrayList();
//add allowed IP's or IP's from CIDR range

//fetch the IP and compare with the whiteListIp list
Mono<MatchResult> ipMatch = Mono.just(exchange)
                .map(ServerWebExchange::getRequest)
                .map(ServerHttpRequest::getRemoteAddress)
                .map(InetSocketAddress::getAddress)
                .filter(h -> {
                    return whiteListIp.contains(h.toString().replace("/", ""));
                })
                .flatMap($ -> MatchResult.match())
                .switchIfEmpty(MatchResult.notMatch());