CSRF: The Impersonation Attack

CSRF: The Impersonation Attack in JavaScript: Imagine you are logged into your bank. You then visit a "Funny Cat Pictures" website.

Concept Explanation

Imagine you are logged into your bank. You then visit a "Funny Cat Pictures" website. The cat website has a hidden button that, when you click it, sends a request to your bank: "Transfer $1,000 to the attacker." Because you are already logged in, your browser automatically sends your login cookies. The bank thinks YOU sent the request.

The key insight: the attacker never sees your cookie and never reads the response. They do not need to. They only need your browser to send an authenticated request. It is forged authority, not stolen data.

XSS and CSRF are opposites worth keeping straight:

XSSCSRF
Attacker runs codeOn your siteOn their site
Needs your cookie valueYes, it steals itNo, the browser attaches it
Fixed byEscaping outputProving intent

Syntax or Core Structure

The attack, in full

<!-- On evil-cats.com. No JavaScript required. -->
<form action="https://bank.com/transfer" method="POST" id="f">
  <input type="hidden" name="to" value="attacker" />
  <input type="hidden" name="amount" value="1000" />
</form>
<script>document.getElementById('f').submit();</script>

The defense in Express

// 1. Cookies that refuse to travel cross-site
app.use(session({
  cookie: { httpOnly: true, secure: true, sameSite: 'lax' }
}));

// 2. A token the attacker's page cannot read
app.use(csrfProtection);
app.get('/form', (req, res) => res.render('form', { token: req.csrfToken() }));

The Defense: CSRF Tokens

The server gives your website a "Private Key" (the Token). Every time you send a request (like transferring money), you must include this key. The "Cat Website" doesn't have the key, so the bank will reject their fake request.

Why can't the attacker read it? Because the Same-Origin Policy stops JavaScript on evil-cats.com from reading the HTML of bank.com. They can send blind requests, but they cannot see what came back.


Real World Example

SameSite Cookies: Modern browsers now default to SameSite=Lax, which prevents cookies from being sent on "Cross-site" requests. This has made many old CSRF attacks impossible!

But Lax is not a complete fix. It still allows cookies on top-level GET navigations, so any state-changing endpoint reachable by GET remains exposed. That is one more reason GET must never modify data.


Common Mistakes

  • Using GET for state changes. A /delete?id=5 endpoint can be triggered by an <img src> tag on any page on the internet.
  • Storing the token in a cookie alone. If the cookie is the only check, the browser sends it automatically and you have proven nothing. The token must arrive in a place only your own page can fill: a header or a form field.
  • Assuming an API is immune because it returns JSON. If it accepts application/x-www-form-urlencoded or reads cookies for auth, a plain HTML form can reach it.
  • Relying on Origin alone. Some older clients and privacy tools strip it, so treat a missing Origin carefully rather than as a pass.

Best Practices

  • Set SameSite=Lax (or Strict for pure first-party apps) plus HttpOnly and Secure on every session cookie.
  • Add a CSRF token for anything cookie-authenticated that changes state. Belt and braces.
  • Prefer Authorization: Bearer headers over cookies for APIs. Headers are not sent automatically, so CSRF largely evaporates.
  • Verify Origin on the server as a cheap second layer.
  • Re-authenticate for the truly dangerous actions: password change, email change, large transfers.

Practice Exercises

  1. The Token Flow: Draw a diagram showing how a server generates a token, the client stores it, and the client sends it back.
  2. The Header Check: Research why checking the Referer or Origin header is a good (but not perfect) defense against CSRF.
  3. The Helmet: Research the helmet package for Express and list 3 security headers it adds automatically.