Home > Back-end >  Spring Security 6.0 CsrfToken behavior change
Spring Security 6.0 CsrfToken behavior change

Time:11-23

I tested Spring Security as part of my Spring Boot Setup in version 6.0-M5, 6.0-RC1 and 6.0-RC2. I recognized a behavior change and wanted to ask whether this may be a bug. I return the CSRF token as a serialized JSON, but since RC1 the content of the token in the JSON is garbage.

My working code in Spring Boot 6 Milestone 5 still working as expected.

@RestController
public class CsrfController {

    @GetMapping("/rest/user/csrf")
    public CsrfToken csrf(CsrfToken token) {
        return token;
    }

}

In my use case I query the controller using a unit test.

    @LocalServerPort
    int serverPort;

    @Autowired
    private TestRestTemplate webclient;

    @Test
    public void getCsrf() {
        ResponseEntity<String> entity = webclient.getForEntity("http://localhost:"   serverPort  
            "/rest/user/csrf", String.class);

        // ... here some code to get the token from the JSON body ...

        assertTrue(result.matches("^[a-f0-9\\-] $"));

This is the first query of the server. A session object between client and server is not established in past queries. This worked in M5 but stopped working in Spring Boot 6 RC1 and RC2

The following controller code made it work again in RC2:

    @GetMapping("/rest/user/csrf")
    public CsrfToken csrf(HttpServletRequest request, HttpServletResponse response) {

        CsrfToken repoToken = tokenRepo.loadToken(request);
        if (repoToken != null) {
            return repoToken;
        }
        // required because it is required but ay not be initialized by the tokenRepo
        request.getSession();

        repoToken = tokenRepo.generateToken(request);
        tokenRepo.saveToken(repoToken, request, response);
        return repoToken;
    }

If I tried the old code in RC2, I received on client side a malformed string. I did not receive a UUID styled token in my JSON serialized response body. I think it is related to the uninitialized session object.

Is this a bug or is an uninitialized session and a resulting not working CrsfToken specified behavior?

CodePudding user response:

I think the issue is in the way I try to get and use the XSFR token.

Because I want to use an Angular frontend, I configured my token repository to provide the tokens via Cookie.

http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

This produces cookies the old UUID style. However the authentication expects the new tokens as generated by https://github.com/spring-projects/spring-security/issues/11960 . Probably the cookie mechanism still needs to be migrated until final Spring Boot 3.0.

  • Related