javaspringspring-security

How to allow all and any requests with Spring Security?


I've just added Spring Security to my project. I've also added this configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }

}

but now not all of my endpoints work. In fact only a single endpoint works, for the rest I get 403 Forbidden. What could be the problem? How can I allow any and all requests (effectively making security a pass-through).


Solution

  • If you want to allow some URL to be accessed without authentication, it is a better practice to prepare some whitelist and pass it to the method antMatchers().

    The antMathers() accepts wild cards as well. If you surely don't want any of the endpoints to be authenticated put /**. But you already have Spring Security, why not use the full power of it.

    Here is a simple way of doing it.

    private static final String[] AUTH_WHITELIST = {
       "/v2/api-docs", "/swagger-resources", "/swagger-resources/**",
    };
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .antMatchers("/csrf").permitAll()
                .anyRequest().authenticated(); 
    }