4

I'm going through the following security tutorial and it configures a CsrfTokenRepository like this:

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

Is that all that is required to get Ajax requests working across all libraries? The Angular documentation for $http says that Angular reads the CSRF cookie that Spring provides and sets a corresponding a header when it makes requests. So I'm assuming it does this because the cookie will not automatically be included when sending Ajax requests?

[Update]

I read the article again and it says that the CSRF protection is provided by the header. So if I interpret that the right way it's the fact that the client is sending back the cookie value in a unique way that is different than it was sent in the first place that provides the CSRF protection. In other words the client receives the cookie and changes the way it is sent back, so that the server knows that the client is indeed in control of the cookie?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

4

CSRF protection with Spring CookieCsrfTokenRepository works as follows:

  1. Client makes a GET request to Server (Spring backend), e.g. request for the main page
  2. Spring sends the response for GET request along with Set-cookie header which contains securely generated XSRF Token
  3. Browser sets the cookie with XSRF Token
  4. While sending state changing request (e.g. POST) the client (Angular) copies the cookie value to the HTTP request header
  5. The request is sent with both header and cookie (browser attaches the cookie automaticaly)
  6. Spring compares the header and the cookie values, if they are the same the request is accepted, otherwise 403 is returned to the client

Note that only state changing requests (POST, PUT, DELETE) are CSRF protected by default and only these need to be protected when API is properly designed (i.e. GET requests don't have side effects and modify the state of the app for example).

The method withHttpOnlyFalse allows angular to read XSRF cookie. Make sure that Angular makes XHR request with withCreddentials flag set to true.

frenchu
  • 288
  • 3
  • 9