-
Notifications
You must be signed in to change notification settings - Fork 41.6k
Description
Status Quo
WebMvcTypeExcludeFilter picks up web-specific components for the web testing slice, but it currently does not include @EnableWebSecurity configuration classes, which are for the web (albeit for security in the web tier).
The Javadoc for @WebMvcTest states that it "can be used when a test focuses only on Spring MVC components." This is, however, in slight contradiction to the subsequent claim that "by default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc."
The aforementioned claims in the Javadoc lead the user to believe that their own Spring Security configuration will be used, thereby requiring roles and authentication mechanisms known to the user. Furthermore, the user naturally assumes that authentication will not be required to access paths for which he or she has not required authentication.
On the contrary, since the user's custom @EnableWebSecurity is not included in the @WebMvcTest slice, Spring Boot configures HTTP BASIC authentication for all request paths.
Consequently, when a user uses @WebMvcTest and then executes a MockMvc test -- without supplying the BASIC authentication headers -- the test fails with a 401 response status (Full authentication is required to access this resource). This can be extremely baffling to the user, especially for non-secured paths such as a home page, login page, etc.
Setting the @WebMvcTest.secure flag to false turns off Spring Security entirely, but that is often undesirable.
Known Workarounds
In my Spring Events sample application, I came up with the following two workarounds.
Generic solution:
@WebMvcTest(includeFilters = @Filter(classes = EnableWebSecurity.class))Custom solution specific to my project:
@WebMvcTest
@Import(WebSecurityConfig.class)Note that WebSecurityConfig is annotated with @EnableWebSecurity.
Related Discussions
- Testing security in Spring Boot 1.4 on Stack Overflow
Proposals
- Whenever
@WebMvcTest.secureis set totrue, include@Configurationclasses annotated with@EnableWebSecurityinWebMvcTypeExcludeFilter.- Alternatively, introduce a new boolean flag or enum to enable automatic inclusion of user-defined
@EnableWebSecurityclasses.
- Alternatively, introduce a new boolean flag or enum to enable automatic inclusion of user-defined
- The Javadoc for
@WebMvcTest.secureshould be augmented to point out that setting it tofalseactually disables auto-configuration for Spring Security completely, instead of implying that it only disables Spring Security Test support inMockMvc.