Loading pattern...

What is CSRF Protection?

CSRF (Cross-Site Request Forgery) is an attack where a malicious site tricks your browser into making an unwanted request to a site you're logged into—like transferring money, changing email, or deleting data. Works because browsers auto-send cookies with requests. Prevent with CSRF tokens (random secret in forms) and SameSite cookies (block third-party requests).

When Should You Use This?

Protect all state-changing actions (POST, PUT, DELETE requests) with CSRF tokens. Use SameSite=Lax or Strict on session cookies to block cross-site requests. Most frameworks have CSRF protection built-in (Django, Rails, Laravel)—enable it. For APIs consumed by your own frontend, use SameSite cookies. For public APIs, use token-based auth (JWT, API keys) instead of cookies.

Common Mistakes to Avoid

  • Not using CSRF tokens on forms—attackers can forge POST requests to change user data
  • Relying on referrer header—easy to spoof; use CSRF tokens
  • Not setting SameSite on cookies—browsers send cookies to third-party sites by default
  • Accepting GET requests for state changes—GET should be safe; use POST/PUT/DELETE
  • Forgetting about AJAX requests—include CSRF token in AJAX headers (X-CSRF-Token)

Real-World Examples

  • Netflix (2006)—CSRF let attackers add DVDs to any user's queue
  • ING Direct (2007)—CSRF transferred money from victim accounts
  • Django—built-in CSRF middleware with {% csrf_token %} template tag
  • Rails—automatic CSRF protection with protect_from_forgery in controllers

Category

Cybersecurity

Tags

csrfcross-site-request-forgerycsrf-tokensamesite-cookiesweb-security

Permalink