A8 – Preventing CSRF

When Web applications don't use a per-session or per-operation token or if the token is not correctly implemented, they may be vulnerable to cross-site request forgery and an attacker may force authenticated users to do unwanted operations.

CSRF is the eighth most critical vulnerability in Web applications nowadays, according to OWASP, and we will see how to prevent it in our applications in this recipe.

Preventing CSRF is all about ensuring that the authenticated user is the one requesting the operation. Due to the way browsers and web applications work, the best choice is to use a token to validate operations or, when possible, a CAPTCHA control.

As attackers are going to try to break the token generation or validation systems, it is very important to generate them securely, in a way that attackers cannot guess them, and make them unique for each user and each operation because reusing them voids their purpose.

CAPTCHA controls and reauthentication are at some point, intrusive and annoying for users, but if the criticality of the operation is worth it, they may be willing to accept them in exchange for an extra level of security.

There are programming libraries that may help in the implementation of CSRF protections, saving tons of work of developers. One such example is the CSRF Guard from OWASP: https://www.owasp.org/index.php/CSRFGuard.