2
votes

Is it a good practice to save the csrf token in a cookie or is it better to use a hidden field in a form? Also is it good to regenerate csrf token every user request like what captchas are doing?

Thanks

3
I'm no expert in all the subtleties, but to me it would seem counter productive to save it in a cookie. If the user has recently been to the site, he has the correct cookie to bypass the check. If you put it in the form, you know that that very form and nothing else generated the cookie.Joachim Isaksson
how about adding the csrf token in the query string instead of a hidden filed do you think that's better that using cookie? Thanksginad

3 Answers

0
votes

It is best to include it in the form. The idea behind a CSRF token is that it is not passed passively (e.g. if a malicious user is able to trick the browser into accessing some URL that does something nasty). Cookies are passed passively.

0
votes

The best explaination to this question can be found on OWASP website at OWASP CSRF Prevention Cheat Sheet page.

Firstly, using cookie for a CSRF token can not help much because all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request.

Secondly, the application can include hidden input parameter in the form with a common name such as "CSRFToken". The value of this token must be randomly generated such that it cannot be guessed by an attacker.

Furthermore, Challenge-Response is another defense option for CSRF. It can be implemented in following ways:

  1. CAPTCHA
  2. Re-Authentication (password)
  3. One-time Token
0
votes

The CSRF cookie is certainly open to attack but implementation safe as the session value will always be checked against a submitted token value either stored in the body or header of the request so I can't see a reason against. The double submit (http only cookie vs post data) or token synchronizer (session vs post data) patterns outlined on the OWASP website are good pratices and both use cookies.

Double submit as mentioned earlier moves the storage to the client so is considered stateless but either way two tokens for comparison, of which one always remains unknown to the attacker.