← Back to Node.js, page 8

nodejs-0159 · Medium mid

What is CSRF, and how do SameSite cookies, CSRF tokens and Origin checks protect a Node.js app?

CSRF makes a victim's browser send a state-changing request to your site, and the browser attaches the victim's cookies. Defend with SameSite=Lax or Strict cookies, a CSRF token that the attacker's page cannot read (synchroniser or double-submit token), a check of the Origin or Referer header, and never changing state with GET. APIs that use an Authorization header instead of cookies are not exposed to classic CSRF.

Full answer

The attack

  • You are logged in to bank.example (cookie session). You visit evil.example, which contains a hidden form that posts to bank.example/transfer. The browser sends the bank cookie with that request, so the bank thinks you made it.
  • CORS does not stop this. A cross-site form post is a simple request, and the server still runs it. CORS only controls who can read responses.

Defences (use several)

  1. SameSite cookies: SameSite=Lax (the default in modern browsers) stops cookies on cross-site POST requests. Strict stops them on all cross-site requests. This is the first line, but not enough alone (older browsers, subdomain issues, same-site attacks).
  2. CSRF token: a random value tied to the session, sent in a hidden form field or custom header and checked on every unsafe method (POST, PUT, PATCH, DELETE). The attacker cannot read it, because the same-origin policy blocks reading your pages. Two styles: synchroniser (stored in the session) and double submit (a cookie value must equal the header value, ideally signed).
  3. Origin check: for unsafe methods, require that Origin (or Referer) matches your site. Requests without both may be rejected.
  4. Custom header requirement (such as X-Requested-With) forces a CORS preflight for cross-site calls.
  5. Do not change state with GET. Re-authenticate for critical actions.

Notes

  • Token-based APIs that send Authorization: Bearer manually from JavaScript are not affected, since the browser does not attach that header automatically. If the token is in a cookie, CSRF applies again.
  • XSS defeats CSRF protection, because injected script can read tokens. Fix XSS too.
  • Libraries: csrf-csrf, csrf-sync (the old csurf package is deprecated).
javascript
const express = require('express');
const crypto = require('node:crypto');

const app = express();
app.use(express.json());
const sessions = new Map();          // session id -> { user, csrf }

function csrfGuard(req, res, next) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
  const origin = req.get('origin');
  if (origin && origin !== 'http://bank.example') return res.status(403).json({ error: 'bad origin' });
  const session = sessions.get(req.get('cookie')?.match(/sid=([^;]+)/)?.[1]);
  const token = req.get('x-csrf-token');
  if (!session || !token || token.length !== session.csrf.length || !crypto.timingSafeEqual(Buffer.from(token), Buffer.from(session.csrf))) {
    return res.status(403).json({ error: 'missing or wrong csrf token' });
  }
  req.session = session;
  next();
}

app.post('/login', (req, res) => {
  const sid = crypto.randomBytes(8).toString('hex');
  const csrf = crypto.randomBytes(16).toString('hex');
  sessions.set(sid, { user: 'asha', csrf });
  res.set('Set-Cookie', `sid=${sid}; HttpOnly; SameSite=Lax; Path=/`).json({ csrfToken: csrf });
});
app.post('/transfer', csrfGuard, (req, res) => res.json({ ok: true, user: req.session.user, amount: req.body.amount }));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const login = await fetch(base + '/login', { method: 'POST' });
  const cookie = login.headers.get('set-cookie').split(';')[0];
  const { csrfToken } = await login.json();
  console.log('cookie attributes:', login.headers.get('set-cookie').split('; ').slice(1).join(' | '));

  const transfer = async (label, headers) => {
    const res = await fetch(base + '/transfer', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ amount: 50 }) });
    console.log(label.padEnd(36), res.status, JSON.stringify(await res.json()));
  };
  await transfer('legitimate (cookie + token)', { cookie, 'x-csrf-token': csrfToken });
  await transfer('forged: cookie only, no token', { cookie });
  await transfer('forged: cookie + wrong token', { cookie, 'x-csrf-token': 'a'.repeat(32) });
  await transfer('forged: token but evil origin', { cookie, 'x-csrf-token': csrfToken, origin: 'http://evil.example' });
  server.close();
});

The server accepts a request only when the cookie, the token and the origin all agree. Forged requests carry the cookie but fail the other checks. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): cookie attributes: HttpOnly | SameSite=Lax | Path=/ legitimate (cookie + token) 200 {"ok":true,"user":"asha","amount":50} forged: cookie only, no token 403 {"error":"missing or wrong csrf token"} forged: cookie + wrong token 403 {"error":"missing or wrong csrf token"} forged: token but evil origin 403 {"error":"bad origin"}

Key points

  • CSRF abuses cookies that the browser sends automatically.
  • CORS does not prevent CSRF.
  • SameSite=Lax or Strict is the first defence.
  • A token the attacker cannot read, plus an Origin check, is the second.
  • Never change state with GET.

Common mistakes

  • Believing that CORS settings stop CSRF.
  • Changing state with GET requests.
  • Using SameSite alone and skipping tokens for sensitive actions.
  • Comparing tokens with === instead of a constant-time comparison.
  • Forgetting XSS, which can read the token.

Follow-ups

  • What is the difference between synchroniser and double-submit tokens?
  • Why are Bearer-header APIs not vulnerable to classic CSRF?
  • How does SameSite=Lax treat top-level GET navigation?

Tips

  • Describe the attack in one sentence.
  • Say 'CORS does not prevent it'.
  • Name three defences.