AuthorizationManager hasIpAddress unable to get to work with more than 1 ip address

44 Views Asked by At

I've been playing with spring-boot-starter-security and i've managed to get my Rest Controller to work with 1 IP whitelist, but unable to make it with many, since i need to adjust input to list from where I am only seeing red in terminal. I am even on the right path?

public class SecurityConfig {

    // GET THE Whitelisted IP value from the application.properties:
    @Value("${allowed.ip.address}")
    private String allowedIpAddress;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
            .anyRequest().access(hasIpAddress(allowedIpAddress))
            )
            .formLogin((form) -> form
                .loginPage("/login")
                .permitAll()
            )
            .logout((logout) -> logout.permitAll());

        return http.build();
    }

     private static AuthorizationManager<RequestAuthorizationContext> hasIpAddress(String ipAddress) {
        IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(ipAddress);
        return (authentication, context) -> {
            HttpServletRequest request = context.getRequest();
            return new AuthorizationDecision(ipAddressMatcher.matches(request));
        };
    }


}

I've tried configurations which i found on the official spring boot site, but were all returning to errors.

1

There are 1 best solutions below

0
rokkotnik On

Got the solution:

@Value("#{'${allowed.ip.address}'.split(',')}")
private List<String> allowedIpAddress;


private static AuthorizationManager<RequestAuthorizationContext> hasIpAddress(List<String> ipAddresses) {
        return (authentication, context) -> {
            HttpServletRequest request = context.getRequest();
            for (String ipAddress : ipAddresses) {
                IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(ipAddress);
                if (ipAddressMatcher.matches(request)) {
                    return new AuthorizationDecision(true);
                }
            }
            return new AuthorizationDecision(false);
        };
    }