Home > Back-end >  CSRF protection with Angular Spring Boot REST JWT
CSRF protection with Angular Spring Boot REST JWT

Time:08-09

I am working with an Angular Spring Boot application and I use JWT for authorization (token stored in an http only cookie), the backend is fully developed with REST services. Now I am trying to use CSRF protection with Spring Security but I don't understand how it works. A new XSRF-TOKEN is always generated for each request, but even if you change it manually or delete it, subsequent requests are always successful.

This is my code snippet regarding CSRF (i.e. what is written on all the guides):

http = http.cors().and().csrf().csrfTokenRepository(this.getCsrfTokenRepository());

...

private CsrfTokenRepository getCsrfTokenRepository() {
    CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
    tokenRepository.setCookiePath("/");
    return tokenRepository;
}

Where am I doing wrong?

CodePudding user response:

You are not doing anything wrong. When you configure CookieCsrfTokenRepository with withHttpOnlyFalse, it means you use double submit cookie approach for CSRF validation rather than typical synchronizer pattern.

In synchronizer pattern, incoming token is matched with the one stored in session. While with CookieCsrfTokenRepository, it is checked if there is cookie named CSRF_TOKEN and a header name X_XSRF_TOKEN and if their values match. Please note cookie name and header name may not be exact, but the point here is there is no specific value in session to be matched against.

It means if I send a token with value A or cookie with value A (A is different than the one stored in cookie sent by Spring security), request will pass because it only checks if header and cookie value are same, not the one it generated.

This is not a security flaw. This is how double submit cookie approach works.

  • Related