Skip to content

WebTestUtils mutates a final SecurityContextHolderFilter field #19520

Description

@gregjotau

Describe the bug

WebTestUtils.setSecurityContextRepository replaces SecurityContextHolderFilter.securityContextRepository through ReflectionTestUtils.setField. That field is final. On current JDKs this emits a restricted final-field mutation warning, and the JDK warning states that this mutation will be blocked in a future release.

WARNING: Final field securityContextRepository in class
org.springframework.security.web.context.SecurityContextHolderFilter has been mutated reflectively by
org.springframework.util.ReflectionUtils
WARNING: Mutating final fields will be blocked in a future release unless final field mutation is enabled

To reproduce

  1. Build a Spring Boot MVC application on JDK 26 with spring-security-test.
  2. Configure MockMvc with SecurityMockMvcConfigurers.springSecurity().
  3. Execute a request that uses a test security context.

The warning is emitted from WebTestUtils.setSecurityContextRepository. The existing WebTestUtilsTests.setSecurityContextRepositoryWhenSecurityContextHolderFilter also exercises this reflective write.

Expected behavior

Spring Security test support should replace the repository through a supported API rather than mutating a final field reflectively.

Proposed solution

Add a null-checked setSecurityContextRepository method to SecurityContextHolderFilter, make the backing field non-final, and have WebTestUtils call the setter. Keep reflective reads unchanged to avoid broadening the production API further. Add/adjust tests for the setter and utility path.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions