How do I use IPwhitelisting and OAuth2 in spring boot?

Viewed 362

I am using OAuth2 in my spring boot application and I want to use IP whitelisting for range of IP addresses. i.e I want to give whitelisted user to access particular resource without providing token. I have large number of whitelisted IPs and I am using Oauth2 token validation so that I have one resource server. I want to use IP whitelisting at first place and if it fails user should have valid token to have access to resource. Can you please give me any idea how can I do that.

1 Answers

In Spring Security you can configure your particular end point and whitelist using the method hasIpAddress in security config class.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/api/**").hasIpAddress("11.11.11.11")
          .anyRequest().authenticated()
          .and()
          .formLogin().permitAll();
    }
}

If you have multiple IP addresses then you can use in this way

http
    .authorizeRequests()
    .antMatchers("/api/**").access(
            "hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')")

For Resource Server you can do it in the @EnableResourceServer class & the same configure method you can setup Ipwhitelisting as shared below

    @Configuration
    @EnableResourceServer
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(new OAuthRequestedMatcher())
                    .anonymous().disable().authorizeRequests();
    http
    .authorizeRequests()
    .antMatchers("/api/**").access("hasIpAddress('10.0.0.0/16') or hasIpAddress('127.0.0.1/32')");
        }
    }

Now since you have mentioned that you have many IP addresses you can make a list in the property file (application.properties) & at the application startup, you can loop through those to build the argument string that has to be passed in the access method.

Related