Search code examples
laravelsecuritycookiescsrfcsrf-token

What is the point of X-CSRF-TOKEN or X-XSRF-TOKEN, why not just use a strict same site cookie?


Frameworks such as laravel and others require you place the csrf token in your HTML forms.

However at the same time laravel comes by default with the VerifyCsrfToken middleware that automatically creates a X-XSRF-TOKEN cookie with the csrf token on every response. This cookie is used for ajax requests and is automatically added to the header for axios for example.

I am wondering why is it required to add the csrf token to every HTML form. Why could you not just use the already existing X-XSRF-TOKEN cookie to validate the csrf token. I understand there is the issue of same site cookies, and if your csrf cookie is set to lax or none the cookie would be sent from an external site if they would POST to my site. However this issue can be solved by setting the same site to strict then there would be no need to set the csrf token on every form which is kind of annoying to do and remember.

Is there some security concern I am missing on why we just cant use a strict cookie for validating the csrf token?


Solution

  • An X-CSRF-Token protects users against unwanted execution of modifying requests, which are of interest for their side effects (the changes which they make to the server, or the database), not for their response, which the attacker cannot read anyway, by virtue of the CORS protocol.

    A same site cookie would protect even against execution of navigation requests, which do not change anything on the server, but only read data (including X-CSRF-Tokens for subsequent modifying requests), which is then displayed in an HTML page. For example, if stackoverflow.com had same site session cookies, you would not be able to navigate from your webmail site via a mailed link to this StackOverflow question and immediately click to upvote it, because the session cookie would not be included in the navigation request, therefore you would not be logged on at first.

    Note also that same site cookies are excluded from the first request to the target site, but if the target site executes an HTML-based (rather than HTTP-based) redirect, the second request includes the cookie, see SameSite=Strict cookies and cross-site requests with redirections.