Sessions and authorization
Protect cookie requests from CSRF
Use SameSite cookies, origin checks, and anti-CSRF tokens where needed for state-changing browser requests.
8 minute lesson
Browsers automatically attach matching cookies, including when a request begins on another site. That behavior creates cross-site request forgery risk.
SameSite is useful defense in depth but may not cover every application flow. Validate Origin or Fetch Metadata where appropriate and use a proven anti-CSRF token pattern for state-changing requests. Never use GET for actions that change state.
The attacker does not need to read the response if submitting the request changes data.
A synchronizer-token flow puts an unpredictable value in the legitimate page and requires it in the request:
<input type="hidden" name="csrfToken" value="session-bound-token">
The server compares it with a value tied to the session. A cross-site page can submit a form, but the same-origin policy normally prevents it from reading the protected page to obtain the token.
Check the Origin header for sensitive browser requests and reject a mismatched origin. Fetch Metadata headers can provide another signal. Define what happens when older or non-browser clients omit them instead of silently accepting every absence.
CSRF tokens do not cure XSS. Script running on your origin may read page tokens and act as the user. Keep output escaping and Content Security Policy in the wider defense.
Document every cookie-authenticated state transition, not just Books resource routes. Include logout, password and email changes, passkey or MFA enrollment and removal, and federated link or unlink. Login itself can need login-CSRF protection. OAuth callbacks use their transaction’s state and OIDC nonce checks rather than an ordinary form token.
Test missing token, wrong token, wrong origin, a valid same-origin request, and a GET request that must remain read-only.
Lesson completed