1. Overview

In this tutorial, we’re going to take a look at how we can disable Spring Security for a given profile.

2. Configuration

First of all, let’s define a security configuration that simply allows all requests.

We can achieve this by registering a WebSecurityCustomizer bean and ignoring requests for all paths:

@Configuration
public class ApplicationNoSecurity {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
            .requestMatchers(new AntPathRequestMatcher("/**"));
    }
}

Remember that this shuts off not only authentication but also any security protections like XSS.

3. Specify Profile

Now we want to activate this configuration only for a given profile.

Let’s assume we have a unit test suite where we don’t want security. If this test suite runs with a profile named “test”, we can annotate our configuration with @Profile:

@Configuration
@Profile("test")
public class ApplicationNoSecurity {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
            .requestMatchers(new AntPathRequestMatcher("/**"));
    }
}

Consequently, our test environment will differ, which we may not want. Alternatively, we can leave security on and use Spring Security’s test support.

4. Conclusion

In this tutorial, we illustrated how to disable Spring Security for a specific profile.

As always, the complete source code is available over on GitHub.