Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

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.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.