2

The title sums it all up nicely. I'm asking for the conditions that should be met so Spring decides to send back a Set-Cookie:XSRF-TOKEN=... response header.

I can see that lots of my requests are getting back responses with such header while it is not needed. For instance, when I send a GET request it gets a response with that header set even though I had set the X-XSRF-TOKEN for the request. But for the POST request having the mentioned request header will stop Spring from sending back the set-cookie header. So I wonder what are the conditions that should be met so Spring decides to send back one.

Mehran
  • 15,593
  • 27
  • 122
  • 221

1 Answers1

6

I spent some time tracing Spring Security's source code and I managed to find out the answer myself.

First of all, I didn't know how CSRF works and tracing the code helped me understand it completely. And I think this is something worth knowing. Here's the scenario of requests and responses sent and received from CSRF point of view:

  1. The first request is sent to the server. Since it's the first one, it has no cookie or header set.
  2. Regardless of the request's method, the server (in here Spring Security) looks into the incoming request. If there's no cookie sent to the server under the name XSRF-TOKEN, it will generate a SET COOKIE header on the response's way back.
  3. The client receives the cookie and for the second request, it will add a header to the request under the name X-XSRF-TOKEN set to the same value as the cookie received. Of course, the cookie will be sent to the server with the second request automatically.
  4. When the server receives the second request, this time it has a XSRF-TOKEN cookie, so it will look for a X-XSRF-TOKEN header and the request is considered valid only if these two strings match.

And as for the answer to my question, as I mentioned in step two, the cookie is generated if there's no cookie sent (with XSRF-TOKEN name) to the server. And it does not rely on any other factor - what so ever!

Mehran
  • 15,593
  • 27
  • 122
  • 221