spring-projects / spring-projects/spring-security

`exportTestSecurityContext()` should consider the `SecurityContextRepository`

Open
#10,766 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

in: test type: bug
Dominant language
Java
Stars
9.6k
Forks
6.3k
Avg merge
2d 11h
Merged PRs (30d)
52

Description

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

}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating SecurityMockMvcResultHandlers and the ExportTestSecurityContextHandler implementation, then inspect the existing tests for exportTestSecurityContext. Verify how WebTestUtils obtains the SecurityContextRepository and add coverage for requests without @WithSecurityContext; done means the handler exports the repository context when the test holder has no authentication.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
authentication, security, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.