Skip to content

Lesson 5 of 9 · 21m

CSRF: Tokens, SameSite, and Honest State Changes

Cross-site request forgery exploits ambient authority — defend it with unpredictable tokens, correct method semantics, and a clear model of when cookies are sent.

CSRF is the attack where your application cannot distinguish "the user meant to do this" from "another site caused the browser to send the user's cookies." If a banking transfer, admin action, or email change can be triggered by a plain form POST from any other origin, the attacker does not need your password or session ID. The browser helpfully supplies authority.

Never mutate on GET

This is the first audit rule because it is cheap and brutally effective:

// wrong: /admin/user/delete?id=14 can be triggered by an image tag or prefetch
// right: deletion requires POST, plus CSRF validation
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    exit;
}

GET requests are fetched, prefetched, embedded, retried, bookmarked, and crawled. They must be safe. The word "safe" in HTTP means no meaningful state change.

Use synchronizer tokens for browser forms

Generate one unpredictable token per session or per form, render it into the HTML, and compare it on submission:

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

echo '<input type="hidden" name="csrf_token" value="' .
    htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') . '">';
$token = $_POST['csrf_token'] ?? '';
if (!is_string($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
    http_response_code(403);
    exit('CSRF validation failed');
}

random_bytes gives cryptographic unpredictability. hash_equals avoids making comparison timing depend on how many characters matched.

SameSite helps, but it is not the whole answer

SameSite=Lax prevents many cross-site POSTs in modern browsers, while Strict is stronger but can break legitimate navigations. It is still a browser-dependent control around cookie transmission. Tokens prove intent for this specific application and also protect flows where cookies are intentionally sent.

APIs need a different posture

If an API authenticates with cookies, it is in CSRF territory. Require a token header such as X-CSRF-Token in addition to the cookie. If an API uses Authorization: Bearer ... and never ambient cookies, classic CSRF mostly disappears because browsers do not attach bearer tokens automatically — but then token storage and XSS become the dominant concerns.

Rotate and scope without breaking users

Rotating tokens on login is wise. Per-form or per-action tokens reduce replay value but complicate multi-tab UX. A session token is usually enough for ordinary applications when combined with correct method checks and SameSite. High-risk administrative actions can use a distinct token or re-authentication.

The wrong fixes people reach for

Checking Referer can help as a heuristic, but headers may be missing for privacy reasons and attackers controlling subdomains or embedding contexts can complicate assumptions. Checking Origin is useful for modern browsers, especially on JSON endpoints, but do not make it your only legacy defense. A CAPTCHA is not a CSRF token; it proves human friction, not form provenance.

Field notes

  • Verify CSRF before processing uploaded files or large bodies where possible; some handlers consume resources before validation otherwise.
  • Multi-tab failures often mean tokens are being regenerated on every page render rather than at login or explicit rotation points.
  • AJAX forms still need the token; adding X-Requested-With alone is not proof of intent.
  • Login forms need CSRF protection too. Login CSRF can attach a victim's actions to an attacker's account.

Was this lesson helpful?

Sign in to rate