CSRF tokens - how to implement properly?

10,127

Solution 1

You can do either. It depends on the level of security you want.

The OWASP Enterprise Security API (ESAPI) uses the single token per user session method. That is probably a pretty effective method assuming you have no XSS holes and you have reasonably short session timeouts. If you allow sessions to stay alive for days or weeks, then this is not a good approach.

Personally, I do not find it difficult to use a different token for each instance of each form. I store a structure in the user's session with key-value pairs. The key for each item is the ID of the form, the value is another structure that contain the token and an expiry date for that token. Typically I will only allow a token to live for 10-20 minutes, then it expires. For longer forms I may give it a long expiry time.

If you want to be able to support the same form in multiple browser tabs in the same session, then my method becomes a little trickery but could still be easily done by having unique form IDs.

Solution 2

The OWASP Cheat Sheet has the most definitive answers for this sort of thing. It discusses different approaches and balancing of security vs. usability.

In brief they recommend having a single token per (browser) session. In other words in your case the same token is shared among tabs. The cheat sheet also emphasizes that it is very important not to expose your site to cross site scripting vulnerabilities, as this subverts the per session CSRF token strategy.

Share:
10,127
Industrial
Author by

Industrial

I just want to lie on the beach and eat hot dogs. That’s all I’ve ever wanted. Really.

Updated on July 01, 2022

Comments

  • Industrial
    Industrial almost 2 years

    I've just setup a simple CSRF protection in my application. It creates a unique crumb which are validated against a session value upon submitting a form.

    Unfortunately this means now that I can't keep multiple instances (tabs in the browser) of my application open simultaneously as the CSRF crumbs collide with each other.

    Should I create an individual token for each actual form or use a mutual, shared crumb for all my forms? What are common sense here?