Skip to main content

CSRF

Trick users into submitting requests with their authentication session

E.g. Bank Transfer —

  • Click malicious link → Insecure session exploited
  • Victim browser sends request → Sent to trusted site & executed

Attack Vectors

Why it works: Browsers automatically send cookies (including session tokens) with every request to a domain

Common methods:

  • Hidden auto-submit forms on malicious sites
  • Image tags: <img src="https://bank.com/transfer?to=attacker&amount=1000">
  • Malicious links in emails or chat
  • Exploiting XSS vulnerabilities on trusted sites

Attack flow:

  1. Victim is authenticated on legitimate site (has session cookie)
  2. Attacker tricks victim into visiting malicious page or clicking link
  3. Malicious request sent to legitimate site
  4. Browser automatically includes victim's session cookie
  5. Server executes request as if it came from victim

Defenses

CSRF Tokens

  • Server generates unique, unpredictable token per session/request
  • Token embedded in forms/AJAX headers (NOT in cookies)
  • Server validates token matches on state-changing requests
  • Attacker can't read token due to Same-Origin Policy
Set-Cookie: session=abc; SameSite=Strict; Secure; HttpOnly
  • Strict — Cookie never sent in cross-site requests
  • Lax — Cookie sent only on safe methods (GET) from cross-site
  • None — Cookie always sent (requires Secure flag)

Additional Protections

  • Verify Origin/Referer headers match your domain
  • Use POST/PUT/DELETE for state changes (never GET)
  • Require re-authentication for sensitive actions
  • Custom headers for AJAX requests

How CSRF tokens work

  1. Server generate a unique, unpredictable token
  2. Token embedded in every state-changing request (e.g. forms, AJAX calls)
  3. Server check if token in request matches the one in user session
  4. If the token is missing or invalid, the server rejects the request