How to defend against CSRF attacks
· Category: Cybersecurity
Short answer
CSRF tricks authenticated users into performing unwanted actions on a website. Defend with anti-CSRF tokens, SameSite cookies, and origin validation.
Steps
-
Implement synchronizer tokens: Generate a unique, unpredictable token for each session or request. Validate it on the server for every state-changing action.
-
Use SameSite cookies: Set the
SameSiteattribute toLaxorStricton session cookies to prevent them from being sent with cross-site requests. -
Validate Origin and Referer headers: Reject requests that originate from unexpected domains.
-
Require re-authentication: Ask for passwords or MFA confirmation for sensitive actions like password changes or fund transfers.
-
Use custom headers: AJAX requests with custom headers cannot be sent cross-origin without CORS approval, adding a layer of protection.
Tips
- Do not rely solely on POST requests for protection; attackers can forge POSTs.
- Ensure tokens are cryptographically random and tied to the user session.
- Combine defenses rather than depending on a single technique.
Common issues
- Tokens exposed in URLs leaking through browser history or logs.
- Missing token validation on some endpoints due to inconsistent frameworks.
- Overly permissive CORS policies undermining origin checks.