spring-security icon indicating copy to clipboard operation
spring-security copied to clipboard

`exportTestSecurityContext()` should consider the `SecurityContextRepository`

Open marcusdacoregio opened this issue 4 years ago • 1 comments

This PR introduced the SecurityMockMvcResultHandlers with the exportTestSecurityContext method. It works well when using with @WithSecurityContext and the annotation that inherits it.

However, it does not work when not using any of those annotations. In that scenarios, if the Authentication is null inside the TestSecurityContextHolder.getContext(), we should consider looking into the SecurityContextRepository. Something like this:

private static class ExportTestSecurityContextHandler implements ResultHandler {

	@Override
	public void handle(MvcResult result) {
		SecurityContext securityContext = TestSecurityContextHolder.getContext();
		if (securityContext.getAuthentication() == null) {
			SecurityContextRepository securityContextRepository = WebTestUtils.getSecurityContextRepository(result.getRequest());
			securityContext = securityContextRepository.loadContext(new HttpRequestResponseHolder(result.getRequest(), result.getResponse()));
		}
		SecurityContextHolder.setContext(securityContext);
	}

}

marcusdacoregio avatar Jan 18 '22 18:01 marcusdacoregio

We need to be careful with this one. Things to consider: what if TestSecurityContextHolder is populated and nothing is in the Repository. What if NullSecurityContextRepository is used?

rwinch avatar Jun 03 '22 13:06 rwinch