Course contentsShow
← Security
Lesson 865 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

Synchronizer Token Pattern

Implement anti-CSRF tokens in forms and validate them server-side to prevent forged requests.

Synchronizer Token Pattern

What you'll learn: How to use unique, per-request tokens to prove a form submission is genuine and prevent CSRF attacks.


The Synchronizer Token Pattern is the most common defense against CSRF attacks. The core idea: when the server sends a form to the user, it embeds a unique, unpredictable secret token. When the form is submitted, the server checks that the token matches what it expects. Because an attacker on another site can't read or guess this token (thanks to Same-Origin Policy), they can't forge a valid request.

How It Works

  1. Token generation: When rendering a form, the server creates a random token (e.g., a3f8d92b4e...) and stores it in the user's session.
  2. Token embedding: The server includes this token as a hidden field in the form:
    <input type="hidden" name="csrf_token" value="a3f8d92b4e..." />
    
  3. Token validation: On submission, the server compares the submitted csrf_token with the one stored in the session. If they match, the request is legitimate. If not, reject it.

Why It Works

An attacker can trick your browser into sending cookies automatically, but they cannot read the token embedded in your page (blocked by SOP). Without the correct token, their forged request fails validation.

Analogy: Imagine a bouncer at a club who stamps your hand with invisible ink only you can see. When you re-enter, you must show the stamp. An impersonator outside can't see your stamp and will be turned away.

Key Points

  • Tokens must be unpredictable (use cryptographic randomness).
  • Tokens should be tied to the user's session.
  • Validate tokens server-side on every state-changing request (POST, PUT, DELETE).

Key Takeaway: The Synchronizer Token Pattern embeds a secret, per-session token in forms and validates it server-side, ensuring requests originate from your legitimate pages—not forged by attackers.