View Javadoc
1   /*
2    * Copyright 2020 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.security;
18  
19  import java.net.InetAddress;
20  import java.net.InetSocketAddress;
21  import java.util.Optional;
22  import org.springframework.http.server.reactive.ServerHttpRequest;
23  import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
24  import org.springframework.web.server.ServerWebExchange;
25  import reactor.core.publisher.Mono;
26  
27  /**
28   * The type Reactive ip address matcher.
29   *
30   * @author Christian Bremer
31   */
32  public class ReactiveIpAddressMatcher extends IpAddressMatcher implements ServerWebExchangeMatcher {
33  
34    /**
35     * Takes a specific IP address or a range specified using the IP/Netmask (e.g. 192.168.1.0/24 or 202.24.0.0/14).
36     *
37     * @param ipAddress the address or range of addresses from which the request must come.
38     */
39    public ReactiveIpAddressMatcher(String ipAddress) {
40      super(ipAddress);
41    }
42  
43    /**
44     * Checks whether the remote address of the request matches the ip of this matcher.
45     *
46     * @param exchange the exchange
47     * @return {@code true} if the remote adaress matches, otherwise {@code false}
48     */
49    public boolean matchesRemoteAddress(ServerWebExchange exchange) {
50      return Optional.ofNullable(exchange)
51          .map(ServerWebExchange::getRequest)
52          .map(ServerHttpRequest::getRemoteAddress)
53          .map(InetSocketAddress::getAddress)
54          .map(InetAddress::getHostAddress)
55          .map(this::matches)
56          .orElse(false);
57    }
58  
59    @Override
60    public Mono<MatchResult> matches(ServerWebExchange exchange) {
61      return matchesRemoteAddress(exchange) ? MatchResult.match() : MatchResult.notMatch();
62    }
63  
64  }