Skip to content

Export SecurityContext from SecurityContextRepository - #20114

Open
havefunatcode wants to merge 1 commit into
spring-projects:7.0.xfrom
havefunatcode:gh-10766
Open

havefunatcode wants to merge 1 commit into
spring-projects:7.0.xfrom
havefunatcode:gh-10766

Conversation

@havefunatcode

Copy link
Copy Markdown

exportTestSecurityContext() only copied the TestSecurityContextHolder, so a request authenticated with with(user("bob")) or formLogin() exported an empty SecurityContext.

Now, when the TestSecurityContextHolder has no Authentication, the handler loads the SecurityContext from the SecurityContextRepository of the request (via WebTestUtils) and exports it if it has an Authentication.

Cases from the issue:

  • TestSecurityContextHolder populated and nothing in the repository: the TestSecurityContextHolder is exported, same as before. It also wins when the repository holds a different user, so tests using @WithMockUser keep their current behavior.
  • NullSecurityContextRepository: nothing is loaded, so the TestSecurityContextHolder context is exported as before (empty unless something like @WithMockUser populated it). No error.

Tested with new cases in SecurityMockMvcResultHandlersTests and a new SecurityMockMvcResultHandlersNullSecurityContextRepositoryTests. The two repository cases (with(user(..)) and formLogin()) fail without the change. Ran ./gradlew :spring-security-test:check and :spring-security-test:javadoc.

This targets 7.0.x since it's a bug fix. The touched files are the same on main.

Closes gh-10766

exportTestSecurityContext() only copied TestSecurityContextHolder, so
requests authenticated with with(user(..)) or formLogin() exported an
empty SecurityContext.

When TestSecurityContextHolder has no Authentication, load the
SecurityContext from the SecurityContextRepository used by the request
and export it if it has an Authentication. A populated
TestSecurityContextHolder still wins, and an empty result from the
repository (for example NullSecurityContextRepository) keeps the
previous behavior.

Closes spring-projectsgh-10766

Signed-off-by: Lee Taeho <dlxogh439@gmail.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged label Nov 16, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants