Hacker News new | ask | show | jobs
by shkkmo 893 days ago
Why would you ever use a cookies to store a CSRF token? A CSRF token is a per request value and that's not what cookies are designed for. Generally the CSRF token is a hidden value on the login form.
3 comments

Cookies are used for double-submit CSRF protection pattern. One copy of the CSRF token is put into a hidden form field, and the other is in a cookie.

https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Re...

In that case the cookie can at least be scoped to the login form with a Path attribute and limited to the current session, which these aren't. The cookies on https://sentry.io/auth/login/ set without user intervention are valid beyond the current browser session and two of them have durations of a year. One even has Same-Site=Lax!

(It's also not clear to me that cookies are required, if there are other technically sound options that do this without setting cookies.)

If you authenticate users only via Same-Site=Strict cookies you're protected against CSRF in modern browsers: a cross-site request won't have the auth cookie.
Session cookies are often encrypted by frameworks using a server side secret.

This allows storing data such as the CRSF token value to check against the one in the hidden form element or X-CSRF-Token without inserting in a DB every time someone loads up a form.

That's how e.g Rails does it by default:

https://guides.rubyonrails.org/security.html#cross-site-requ...

https://api.rubyonrails.org/classes/ActionController/Request...

Note that to prevent session fixation, the session ought to be reset on a successful login (and logout), so it would require additional code to perform tracking across a successful login.

https://guides.rubyonrails.org/security.html#session-fixatio...

Session cookies are also used for Rails flash messages, commonly used to display errors in forms (including login forms), which often do HTTP redirects to GET routes in their non-GET controller actions.

https://api.rubyonrails.org/classes/ActionDispatch/Flash.htm...

https://api.rubyonrails.org/classes/ActionDispatch/Flash/Req...

https://stackoverflow.com/questions/24877244/rails-is-the-fl...

The underlying subtext is that these session cookies can be a necessity of securing the provided service, and thus can fall under valid "strictly necessary" usage, as long as they are not abused for tracking (by default nothing in the session cookie is stored nor logged anywhere)