Skip to content

exportTestSecurityContext() should consider the SecurityContextRepository #10766

Open
@marcusdacoregio

Description

@marcusdacoregio

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);
	}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: testAn issue in spring-security-testtype: bugA general bug

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions