Describe the bug I'm using CSRF Token to secure my POST Requests I have enabled CSRF together with CookieCsrfTokenRepository.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.authorizeHttpRequests((authz) -> {
authz.requestMatchers("/*").permitAll();
authz.anyRequest().authenticated();
})
.build();
}
When I perform a GET Request I receive an XSRF-Token Cookie with value like e.g. "a4eeed29-e556-4cc2-903a-8dc33c21452b". If i try to use this CSRF Token as Header Parameter e.g. "X-XSRF-TOKEN : a4eeed29-e556-4cc2-903a-8dc33c21452b " i receive always an 403 error, with message "Invalid CSRF token found for". If i log the CSRF Token to the System.out i receive XSRF- Token. I get something like the following X-XSRF-TOKEN = ghGcA26K8onu5eWQNxxm0B3mBkNTiH_PFuDvHKGKsfbCSrLr4yX5ZgvuwLDDgNClATFSs37UK3pjux7iLoSML5Lpg8f2f4CJ. If I use this token as Header Parameter in my POST request I get authenticated and all is fine. Logged the Token on backend side with:
@GetMapping(value = "/hello")
public String getProjects(HttpServletRequest request) {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
System.out.println(token.getHeaderName() + " = " + token.getToken());
return "Hello";
}
Why is CSRF Token logged on backend side not in the same format as the XSRF Cookie ? I expected the XSRF Token to have a format like "a4eeed29-e556-4cc2-903a-8dc33c21452b".
To Reproduce This behaviour is reproducible with Spring Boot 3.0.0 and 3.0.1-SNAPSHOT. In Spring Boot 2.7.7 the XSRF Token has the same format as the XSRF Cookie. That works as expected. Use the attached demo project. Issue an GET Request against http://localhost:8080/hello. This will set the XSRF Cookie. Issue an POST Request against http://localhost:8080/signin using something like Postman and use the value of the Cookie as value of the X-XSRF-TOKEN header parameter, just pass any string in the body. You will receive a 403 error. Compare the Value of the Cookie with the XSRF Token logged in the console by the /hello service.
Expected behavior Why is CSRF Token logged on backend side not in the same format as the XSRF Cookie ? I expected the XSRF Token to have a format like "a4eeed29-e556-4cc2-903a-8dc33c21452b". And why the XSRF Token of the Cookie doesn't work ?
Sample
Sample Project https://github.com/fIannazzo/demo-csrf-bug
Comment From: marcusdacoregio
Hi @fIannazzo, this behavior is described in the Preparing for 6.0 section of the documentation. If you feel that it lacks some information let us know.