How to allow all and any requests with Spring Security?

Viewed 6893

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).

3 Answers

I had to add .csrf().disable() to make it work.

So the whole solution for me was

http.csrf().disable().authorizeRequests().anyRequest().permitAll();

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(); 
}

You can try with

http.authorizeRequests().antMatchers("/**").permitAll();
Related