Disable Spring Security to a specific profile

Disable Spring Security for Specific Profile

Overview

In this post, we will learn to disable spring security for a specific profile and enable it for others.

Let’s say, we have two profiles dev and prod in our spring boot application and we want to disable security in the dev and enable it in the prod.

Spring does not provide auto-configuration for this. So, we have to configure it ourselves.

Solution

In this example, we are using spring boot version 2.3.1.

Spring Security Dependency:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

A code to disable security for a specific profile

@Profile(value = {"dev"})
@Configuration
@Component("disableSecurityBean")
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class DisableSecurity extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**");
    }
}

In this code, we have defined a bean name because it is required if we have another configuration class as a child class of WebSecurityConfigurerAdapter (A configuration class that extends it).

And also given the highest order so that it runs first. This is because we have another configuration class where spring security is implemented.

A class that has configured for security

@Configuration
public class EnableSecurity extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        // implement security here
    }
}

Conclusion

In this post, we learned how to enable and disable spring security on a specific profile.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments