-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Description
Expected Behavior
After calling MockMvc, I want to be able to make assertions that depend on the SecurityContext defined by the test.
Current Behavior
Currently, after performing any MockMvc request, the SecurityContext is cleared by ThreadLocalSecurityContextHolderStrategy#clearContext() which causes the following exception to be thrown when you use SecurityContext dependent code during assertions:
java.lang.IllegalArgumentException: Authentication object cannot be null
Details can be found here in SO: https://stackoverflow.com/questions/51622300/mockmvc-seems-to-be-clear-securitycontext-after-performing-request-java-lang-il/
Context
- Goal: I want to keep the SecurityContext during the whole test execution.
- Workaround: I could disable filters through @AutoConfigureMockMvc(addFilters = false). Does not seem like a nice option in all cases.
- Current solution in my project using a MockMvcBuilderCustomizer
public class MockMvcTestSecurityContextPropagationCustomizer implements MockMvcBuilderCustomizer {
@Override
public void customize(ConfigurableMockMvcBuilder<?> builder) {
builder.alwaysDo(result -> {
log.debug("resetting SecurityContextHolder to TestSecurityContextHolder");
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
});
}
}
Proposal
My proposal is that this propagation could be done by the framework itself in org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration.SecurityMockMvcBuilderCustomizer (or a another separate configuration within MockMvcSecurityConfiguration) but I am not sure if I miss some negative impact by doing that in general.