CSRF protection: do we have to generate a token for every form?

Solution 1:

In general, it suffices to have just one token per session, a so called per-session token:

In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires.

If you want to further enhance the security, you can use one token per each form/URL (per-form token) to mitigate the impact when one token leaks (e. g. XSS) as an attacker would only be able to successfully attack that specific form/URL.

But using per-request tokens, i. e. tokens that change with each request, rather cuts the usability of the website as it restricts parallel browsing:

To further enhance the security of this proposed design, consider randomizing the CSRF token […] for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the "Back" button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server.

So I recommend you to use either per-session tokens or per-form tokens.

Solution 2:

No, you just need to generate a token on a per-session basis.

Tokens are very unlikely to be leaked accidentally by users and generating a token per form makes things very complicated if a user is browsing the site in two different tabs/windows at once.