Disable Spring Security through Java configuration?

I have a Java application that uses Spring Security through a Java configuration.

What is the easiest way to toggle a whole Spring on / off security in compilation?

So, something like this , but for a configuration that does not use XML.

EDIT:

After applying @Profile, my code looks like this:

@Configuration @Profile("SecurityOn") @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

The problem is that if the "SecurityOn" profile is not activated, Spring Security uses some default configuration. Instead, how to disable Spring Security in this case?

+5
source share
2 answers

To disable this behavior, you can add another class that looks like this:

 @Configuration @EnableWebMvcSecurity @Profile("!SecurityOn") public class WebSecurityConfigDisable extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/**").permitAll(); } } 

Then, when you launch the application, the only time you need to log in is the SecurityOn profile. If you use Maven and Spring Boot, then the enable command will be next.

 mvn spring-boot:run -Dspring.profiles.active=SecurityOn 

Running without a profile or another profile will disable . This is useful for local development.

I found this to be necessary when using spring-boot-starter-security , because there was a default setting requiring login.

+4
source

Consider using Profile .

Since @Profile can be used as method-level annotation for any @Bean method, you can use one profile (for example, "safe") and annotate only the corresponding @Bean methods.

Then specify the active profile through any of the properties of the JVM system as an environment variable or for web applications as a servlet context parameter in web.xml

Pay attention to the use of the example here .

0
source

Source: https://habr.com/ru/post/1210093/


All Articles