Spring Boot 2.0.x disable security for certain profile

There is another option to disable security in spring boot 2

@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

Add this over the main class


Here is how I ended up solving the problem. Here is an example of how my security config looked in Spring Boot 1.5.x. Security was disabled with property security.basic.enabled=false:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/upload/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}

Since security.basic.enabled was removed in Spring Boot 2 (but still reserved as property name), I ended up using security.enabled as a custom property. Here's an example of how my config looks in Spring Boot 2:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${security.enabled:true}")
    private boolean securityEnabled;

    @Override
    public void configure(WebSecurity web) throws Exception {
        if (securityEnabled)
            web.ignoring().antMatchers("/upload/**");
        else
            web.ignoring().antMatchers("/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if (securityEnabled)
            http.csrf().disable().authorizeRequests()
                    .anyRequest().authenticated()
                    .and().httpBasic();
    }
}

You have to add a custom Spring Security configuration, see Spring Boot Reference Guide:

28.1 MVC Security

The default security configuration is implemented in SecurityAutoConfiguration and UserDetailsServiceAutoConfiguration. SecurityAutoConfiguration imports SpringBootWebSecurityConfiguration for web security and UserDetailsServiceAutoConfiguration configures authentication, which is also relevant in non-web applications. To switch off the default web application security configuration completely, you can add a bean of type WebSecurityConfigurerAdapter (doing so does not disable the UserDetailsService configuration or Actuator’s security).

For example:

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
               .antMatchers("/**");
    }
}

To use the configuration only for a profile add @Profile to the class. If you want to enable it by property, add ConditionalOnProperty to the class.