Skip to content

CSRF Protection: Stop Unwanted Actions from Another Site

CSRF makes an authenticated browser send an unwanted request. Use SameSite, tokens and origin checks as complementary controls.

Muhammad Azhar August 14, 2026 Editorial date: November 7, 2026 2 min read

Cross-site request forgery abuses a browser that is already authenticated. A malicious page causes the browser to send a state-changing request, and ambient cookies may make it look legitimate.

Protect state changes

  • Use unpredictable anti-CSRF tokens tied to the session.
  • Set appropriate SameSite cookie attributes.
  • Validate Origin or Referer for sensitive requests.
  • Require reauthentication for high-impact changes.
  • Never change state through GET requests.

APIs need context

An API using Authorization headers instead of cookies has a different exposure. CORS is not a universal CSRF defence, and XSS can defeat many in-page controls.

Test like a browser

Verify forms, JSON endpoints, multipart uploads and logout. Framework defaults help only when developers use the intended middleware correctly.

Login CSRF exists too

An attacker may cause a victim to sign into the attacker's account, then collect information the victim unknowingly adds. Protect login and account-linking endpoints, not only obvious payment actions.

Token handling

Do not place anti-CSRF tokens in URLs where logs and referrers may capture them. Compare tokens in constant time where appropriate and rotate them with session boundaries.

Choose a complete token design

Use the framework's maintained CSRF protection. For a stateless double-submit approach, prefer a signed token explicitly bound to the session; a naive cookie-and-form equality check can fail when an attacker can inject a cookie.

Verify rejection and recovery

Test from a different origin and confirm that a forged mutation is rejected. JSON endpoints should require expected content types, and credentialed CORS rules should allow only trusted origins. Keep tokens out of logs and return a clear failure without revealing secret values.

Exercise expired sessions, multiple tabs, authentication callbacks and checkout. Exclude mobile clients or background jobs only after confirming their authentication does not depend on ambient browser cookies, then protect their authorization and replay behavior independently.

Sources and further reading