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

  1. Implement synchronizer tokens: Generate a unique, unpredictable token for each session or request. Validate it on the server for every state-changing action.

  2. Use SameSite cookies: Set the SameSite attribute to Lax or Strict on session cookies to prevent them from being sent with cross-site requests.

  3. Validate Origin and Referer headers: Reject requests that originate from unexpected domains.

  4. Require re-authentication: Ask for passwords or MFA confirmation for sensitive actions like password changes or fund transfers.

  5. 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.