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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With