Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Spring Security config class for @WebMvcTest in Spring Boot

Recently I have added Spring Security to my Spring Boot project using the following class:

@EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class MySecurityConfig { } 

as result, by default all my URLs are now protected with authentication and a self-generated password.

The problem is that all tests in a @WebMvcTest class that I used for unit-testing a controller:

@RunWith(SpringRunner.class) @WebMvcTest(SomeController.class) public class SomeControllerTest {...} 

are now failing everywhere because of lack of authorization.

Question: can I tell @Test methods to ignore authorization so they keep succeeding as before?

How can I prevent the @EnableWebSecurity config class from being picked on a specific @WebMvcTest unit testing class?

I would like the tests already in place to be able to still go through and to test the authentication features separately later on.

So far I have tried to use a nested config class in the testing class in order to exclude security configs:

@RunWith(SpringRunner.class) @WebMvcTest(SomeController.class) public class SomeControllerTest {      @Configuration     @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})     static class ContextConfiguration { }   ....} 

but it seems not to work.

NOTE : I am using Spring Boot 1.5.8

like image 249
Johan Avatar asked Dec 01 '17 12:12

Johan


People also ask

How do I disable spring boot security configuration?

In Spring Boot 2, if we want our own security configuration, we can simply add a custom WebSecurityConfigurerAdapter. This will disable the default auto-configuration and enable our custom security configuration.

How do I disable security in Spring security?

enabled=false and management. security. enabled=false should be set to disable the security.

How do I disable Webmvctest Spring Security?

One of the ways you can disable Spring Security filters in your tests, is to use the @AutoConfigureMockMvc annotation. @AutoConfigureMockMvc annotation can be applied to a test class to enable and configure auto-configuration of MockMvc.


1 Answers

For me in Spring Boot 2.2.4 (JUnit5) the below seems to have worked and bypass the security filter.

@ExtendWith(SpringExtension.class) @WebMvcTest(SomeController.class) @AutoConfigureMockMvc(addFilters = false) public class SomeControllerTest { ... 

Note: this simply disables any filters in the SpringSecurity configuration. It won't disable the security completely. In other words it will still bootstrap security without loading any filters.

like image 172
theo Avatar answered Sep 27 '22 20:09

theo