Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

What Is CSRF? How to Prevent Cross-Site Request Forgery

Learn why cookie-authenticated apps need CSRF defenses and how to protect state-changing actions with tokens, cookie settings, and server checks.

Table of Contents

Cross-site request forgery (CSRF) occurs when an application accepts a state-changing request from a signed-in browser without verifying that the user intended the action. It matters especially for applications that rely on session cookies, because the browser can attach qualifying cookies automatically.

What is CSRF? How it works and how to prevent attacks effectively Picture 1

Why session authentication alone is insufficient

A valid session tells the server which account a request belongs to. It does not always tell the server where the request came from or whether the user initiated the change from the application's interface. A preference update should therefore require both a valid session and the application's CSRF check.

Protect state-changing actions on the server

What is CSRF? How it works and how to prevent attacks effectively Picture 2
Validate CSRF protections for state-changing requests before applying an update.
  1. Enable framework protection. Use the framework's built-in CSRF middleware. Include its token in forms or the required client request header. Reject absent or invalid tokens before processing the update.
  2. Keep GET safe. Use GET to retrieve resources. Use the appropriate write methods for state changes and protect them with CSRF validation. The write method alone does not provide that protection.
  3. Configure session cookies deliberately. Set Secure and HttpOnly where appropriate and choose a SameSite policy that matches your sign-in flow. SameSite provides an extra layer alongside server-side checks.
  4. Check request origin as an additional control. Follow your framework's guidance for trusted origins and reverse proxies. Require reauthentication before particularly sensitive changes, such as updating recovery settings.

Verify your changes before release

In your application's automated tests, assert that write operations reject requests without valid CSRF protection and leave stored data unchanged. Check that your normal form submission, API client, and sign-in or callback flows still work. For framework-independent guidance, see the OWASP CSRF Prevention Cheat Sheet.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.