Skip to content

Include web security configuration classes when @WebMvcTest.secure is true #6514

@sbrannen

Description

@sbrannen

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

  1. Whenever @WebMvcTest.secure is set to true, include @Configuration classes annotated with @EnableWebSecurity in WebMvcTypeExcludeFilter.
    • Alternatively, introduce a new boolean flag or enum to enable automatic inclusion of user-defined @EnableWebSecurity classes.
  2. The Javadoc for @WebMvcTest.secure should be augmented to point out that setting it to false actually disables auto-configuration for Spring Security completely, instead of implying that it only disables Spring Security Test support in MockMvc.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions