Regenerate CSRF token per each request


I found that CSRF token in Yii is generated once and stored in cookie.

Cookie will expire when session expire.

If malicious website has your CSRF token from cookie, it can perform POST request and avoid Yii CSRF protection.

Think that CSRF token should be regenerated per each request.

How other frameworks implement CSRF protection:

What do you think?

how would a malicious website read your CSRF token? If they can do that you have bigger problems to worry about.

Side note: you can use








to mitigate the possibility of stealing the cookie.

Yes, you’re right about that (you’re XSS-ed and prevention was too trivial), but that’s not the point of this topic… point is CSRF token validation. Just imagine they have your CSRF token and they can avoid your CSRF protection.


Think that’s ok.

I would rather suggest session for CSRF token storage than cookie. Or regenerate token on every request.

The problem with regenerating the token on each request is this scenario:

  1. I open and start writing a long, long blog post.

  2. In the middle of writing the post, I notice there are some comments on another post pending approval, I right click the link and open it in a new tab.

  3. I approve some comments and close that tab

  4. I continue writing my blog post, 10000 words later I click "Publish"

  5. Since my CSRF token has expired, I get an exception when I post and I lose all my work.

This also applies to storing the CSRF token in the session. At least if a session expires while the user is filling out a form the CSRF token won’t expire, and we can store their submission and post it after they log back in. If the CSRF token is in the session, we won’t be able to trust that that input really came from the user.

The fact is, if a malicious website can read your cookies, you’re already screwed and CSRF protection is only going to slow them down, not stop them.

If you regenerate the token on each request i would like to see you working with multiple ajax calls ;) you will pull your hair out, i guarantee it.