Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot 2.1 - @WebMvcTest without Spring Security Auto-Configuration

Tags:

Before migrating to Spring Boot 2.1, we had a couple of controller tests in our services utilizing @WebMvcTest in combination with @AutoConfigureMockMvc:

@WebMvcTest(SomeController.class)
@AutoConfigureMockMvc(secure = false)
public class SomeControllerTests { ... }

This had the effect that the Spring Security configuration was disabled and you could run MVC tests without mocking OAuth/JWT.

In Spring Boot 2.1, the secured attribute is deprecated and the release notes mention that

[...] @WebMvcTest looks for a WebSecurityConfigurer bean [...].

In order to avoid the deprecated secured attribute and loading of our WebSecurityConfigurer we rewrote our tests to:

@WebMvcTest(
    value = SomeController.class,
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebSecurityConfigurer.class),
    excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
public class SomeControllerTests { ... }

The question is: is there a more compact way in Spring Boot 2.1 to define such tests?

like image 276
Andre Steingress Avatar asked Nov 20 '18 09:11

Andre Steingress


People also ask

How do I disable spring boot security configuration?

To disable Security Auto-Configuration and add our own configuration, we need to exclude the SecurityAutoConfiguration class from auto-configuration. If you have spring-boot-actuator included in your dependecies then you need to exclude ManagementWebSecurityAutoConfiguration class from auto-configuration.

What does the @WebMvcTest annotation auto configure?

By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc (include support for HtmlUnit WebClient and Selenium WebDriver). For more fine-grained control of MockMVC the @AutoConfigureMockMvc annotation can be used.

Is Spring Security necessary?

The Spring Security framework is a reliable way for Java developers to secure applications. However, proper implementation is critical to prevent the most common vulnerabilities.

Is Spring Security enabled by default?

By default, the Authentication gets enabled for the Application. Also, content negotiation is used to determine if basic or formLogin should be used. For more defaults, see the security properties section of the Spring Boot Common Application Properties reference page.


1 Answers

Yes, rather than working around the fact the flag is deprecated, you should embrace the fact that this is going in that direction going forward.

As of Spring Boot 2.1, if you have Spring Security, your tests will be secured using your custom configuration. What is the actual problem with that?

If you don't want to authenticate for certain tests, just use Spring Security's test infrastructure and add @WithMockUser.

like image 192
Stephane Nicoll Avatar answered Sep 16 '22 15:09

Stephane Nicoll