Application Security

Prevent Cross-Site Request Forgery in State-Changing Actions

Use CSRF tokens, SameSite cookies and origin checks to protect authenticated browser actions.

Cross-site request forgery (CSRF) tricks a browser into sending an authenticated request to a site where the user is already signed in. The risk is greatest for actions that change account settings, permissions, payments or content. A request should not be considered intentional merely because it carries a valid session cookie.

Use unpredictable CSRF tokens

Generate tokens with a cryptographically secure random source, bind them to the user's session and validate them on every state-changing browser request. Compare tokens safely and reject missing or invalid values. Tokens should not be placed in URLs where they may leak through logs or referrer data.

Keep HTTP methods meaningful

GET requests should not change server state. Use POST, PUT, PATCH or DELETE for state-changing operations and apply CSRF validation consistently. Do not assume that changing a button to a POST form automatically provides protection.

Add cookie and origin defenses

Set session cookies with Secure, HttpOnly and an appropriate SameSite policy. SameSite is useful defense in depth but should not be the only CSRF control for sensitive workflows or unusual browser contexts. Where appropriate, validate Origin or Referer against the expected site origin.

Test every entry point

Review normal forms, AJAX requests, account actions and administrative endpoints. Ensure token validation occurs before the action executes and that failed validation does not partially change data.

Checklist

  • Require session-bound CSRF tokens for state changes.
  • Never mutate state through GET.
  • Set secure session cookie attributes.
  • Validate origin where appropriate.
  • Test forms, AJAX and administrative actions.
Share this page Help other developers discover this resource.