Fitz
Fitz

Reputation: 85

How to Restrict Access to Resources by IP Address and Credentials in Spring 5.7+

Since WebSecurityConfigurerAdapter from Spring 5.6 has been deprecated, how can we restrict access to web app resources based on a set of IP addresses? My goal is to disable the default spring login form, but still send post requests to the app with certain credentials from only a given set of IP addresses.

I have been following Eugen's example at Baeldung here https://github.com/eugenp/tutorials/blob/4fa0844faf6f95bbde4a38d0b16cde066fd4d8af/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/config/CustomIpAuthenticationProvider.java, which was written for Spring 5.6. I tried upgrading to the SecurityFilterChain recommended here: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter. I then disabled SecurityAutoConfiguration while using @EnableWebSecurity on my class that uses the SecurityFilterChain, but I cannot get my code to work to block requests from certain IP addresses and a given user.

Below is my code.

Main App

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }

}

Configuration Class

@Configuration
@EnableWebSecurity
public class SecurityConfig  {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity security) throws Exception {

        security.csrf().disable().authorizeRequests().anyRequest().permitAll(); // Works for GET, POST, PUT, DELETE
        security.authenticationProvider(new CustomIpAuthenticationProvider());
        security.formLogin().disable();

        return security.build();
    }
}
    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        UserDetails user = User.withUsername("test_user")
                .password(encoder.encode("password"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Custom Authentication Provider

public class CustomIpAuthenticationProvider implements AuthenticationProvider {

    Set<String> whitelist = new HashSet<>();

    public CustomIpAuthenticationProvider() {
        super();
        whitelist.add("11.11.11.11");
//        whitelist.add("0.0.0.0");
//        whitelist.add("127.0.0.1");
    }

    @Override
    public Authentication authenticate(Authentication auth){
        WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
        String userIp = details.getRemoteAddress();

        System.out.println(userIp);

        if (!whitelist.contains(userIp)) {
            throw new BadCredentialsException("Invalid IP Address");
        }

        final String name = auth.getName();
        final String password = auth.getCredentials().toString();

        if (name.equals("test_user") && password.equals("password")) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new UsernamePasswordAuthenticationToken(name, password, authorities);
        }
        else{
            throw new BadCredentialsException("Invalid username or password");
        }


    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
    }

Unit Test to Test App

@Test
    public void givenUserWithWrongIPForbidden() {
        Response response = RestAssured.given().auth().form("test_user", "password")
                .get(base + "/login");

        assertEquals(403, response.getStatusCode());
        assertTrue(response.asString().contains("Forbidden"));
    }

Upvotes: 2

Views: 4815

Answers (2)

Amirhosein Bayat
Amirhosein Bayat

Reputation: 1123

I solved it with this solution in spring security version 6.1

http.authorizeHttpRequests(requests -> requests
                .requestMatchers(
                .requestMatchers(HttpMethod.GET, "/actuator/**").access(new WebExpressionAuthorizationManager("hasIpAddress('127.0.0.1') or hasIpAddress('172.9.9.9')"))

with this configuration you can specify which end point is restricted to which IP list. for this part "hasIpAddress('127.0.0.1') or hasIpAddress('172.9.9.9')" I wrote a function that will generate the restricted IP from List of IPs:

private String convertActuatorIps(List<String> actuatorIps) {
    return actuatorIps.stream()
            .map("hasIpAddress('%s')"::formatted)
            .collect(Collectors.joining(" or "));
}

and

.requestMatchers(HttpMethod.GET, "/actuator/**").access(new WebExpressionAuthorizationManager(convertActuatorIps(allowedActuatorOrigins)))

Upvotes: 0

Rodrigo Souza
Rodrigo Souza

Reputation: 13

I had the same problem. I ended up changing my mind and used a filter. Here's an example

Upvotes: 1

Related Questions