Description
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
- We are using Cookies for CSRF via CookieCsrfTokenRepository.withHttpOnlyFalse()
- We are using SecurityMockMvcRequestPostProcessors.csrf() to populate our mock-requests
- We are basically using this security-configuration: https://docs.spring.io/spring-security/reference/5.8/migration/servlet/exploits.html#_i_am_using_angularjs_or_another_javascript_framework
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