Course contentsShow
← Computer Science
Lesson 2467 of 2,87255. Web SecurityFree lesson

CSRF Token Defense

Using synchronizer tokens to prevent CSRF: generating unique per-session tokens that attackers cannot predict or obtain.

CSRF Token Defense

What you'll learn:
You'll learn how to use unique synchronizer tokens to block CSRF attacks by making malicious requests fail authentication.

The Core Defense Strategy

After understanding how CSRF attacks exploit trust between a user's browser and a website (lessons 2464–2466), the most effective countermeasure is the synchronizer token pattern. This defense works by embedding a secret, unpredictable value in every form or state-changing request that attackers cannot forge.

How Synchronizer Tokens Work

When a user visits your site, the server generates a unique, random token tied to that user's session. This token is:

  1. Stored server-side (in the session)
  2. Embedded in the page (usually as a hidden form field or custom HTTP header)
  3. Submitted with every request that changes data (POST, PUT, DELETE)

When the server receives a state-changing request, it compares the submitted token with the session's stored token. If they match, the request proceeds. If they don't match or the token is missing, the request is rejected.

Why This Stops CSRF

An attacker crafting a malicious request from evil.com cannot read or predict your token because:

  • Same-origin policy prevents JavaScript from reading pages across domains
  • Tokens are cryptographically random and change per-session
  • The attacker has no way to extract the token from the legitimate page

Think of it like a concert wristband: the venue (server) gives you a unique wristband (token) when you enter. Every time you order a drink (make a request), staff check your wristband. An outsider shouting drink orders from outside the venue (CSRF attack) doesn't have a valid wristband, so their orders are ignored.

Key Takeaway:
CSRF tokens prevent attacks by requiring a secret, session-specific value that attackers cannot obtain or predict, ensuring only legitimate requests from your actual users succeed.