Skip to content

MockMvc tests not working with CSRF-protected endpoints in spring-security 6 #12774

Closed
@hinnerkoetting

Description

@hinnerkoetting

Describe the bug
We are currently in the process of updating to spring-security 6 and are having trouble with our MockMvc tests that are calling CSRF-protected endpoints with enabled BREACH-protection. We are using CSRF-cookies.
All requests are rejected by the CsrfFilter and status 403 Forbidden.
Our configuration works when using it outside of MockMvc.

To Reproduce

Expected behavior
Requests should not be rejected because of invalid CSRF tokens while using SecurityMockMvcRequestPostProcessors.CsrfRequestPostProcessor.

Possible solution:
To me it seems that the CSRF-token in our Mock-Request is not correctly processed by XorCsrfTokenRequestAttributeHandler.
The following change in SecurityMockMvcRequestPostProcessors.CsrfRequestPostProcessor fixes the issue for us:

         CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
-        String tokenValue = this.useInvalidToken ? INVALID_TOKEN_VALUE : token.getToken();
+        String tokenValue = this.useInvalidToken ? INVALID_TOKEN_VALUE : deferredCsrfToken.get().getToken();
         if (this.asHeader) {

Sample
There is a writeup on stackoverflow with a similar issue:
https://stackoverflow.com/questions/74729765/csrf-in-tests-stopped-working-with-spring-boot-3-and-spring-security-6

Metadata

Metadata

Labels

in: testAn issue in spring-security-teststatus: declinedA suggestion or change that we don't feel we should currently applytype: bugA general bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions