The Problem
After performing any MockMvc request, the SecurityContext is cleared using ThreadLocalSecurityContextHolderStrategy#clearContext() which cause the following exception to be thrown when I try to call repository.findAll();
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/
I think a fine solution would be to add a MockMvcBuilderCustomizer
that sets the SecurityContextHolder again after each MockMvc call.
The possible solution
I have successfully solved the issue using this code in our project:
public class MockMvcTestSecurityContextPropagationCustomizer implements MockMvcBuilderCustomizer {
@Override
public void customize(ConfigurableMockMvcBuilder<?> builder) {
builder.alwaysDo(result -> {
log.debug("resetting SecurityContextHolder to TestSecurityContextHolder");
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
});
}
}
The proposal
My proposal is that this propagation could be done by 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.
Comment From: wilkinsona
Thanks for the suggestion. I think it would be better if this was addressed in Spring Security as the problem isn't specific to Spring Boot. Anyone using Spring Security and MockMvc will be affected as it's Spring Security code that's both setting and clearing the security context. I'll ask the Security team to take a look and then we can either close this in favour of a Spring Security issue or consider if this is something that has to be addressed in Spring Boot.
Comment From: wilkinsona
@sniffertine I've discussed this with @rwinch and he'd like to address it in Spring Security. Can you please open a Spring Security issue and comment here with a link to it for future reference?
Comment From: sniffertine
This issue was originally comming from here: https://github.com/spring-projects/spring-data-mongodb/issues/2906 I now created another in spring security here: https://github.com/spring-projects/spring-security/issues/9565