Back to all terms
Form+tokenServertoken matchEvil Siteno token!
Securityintermediate

CSRF (Cross-Site Request Forgery) Protection

Mechanisms to prevent unauthorized commands from being transmitted from a user that the web application trusts.

Also known as: XSRF protection, cross-site request forgery, session riding prevention

Description

Cross-Site Request Forgery (CSRF) is an attack that forces an authenticated user to execute unwanted actions on a web application. Since browsers automatically include session cookies with requests to a domain, a malicious site can craft requests that piggyback on the victim's existing authentication. This can lead to unauthorized fund transfers, password changes, data modifications, or any state-changing operation the victim is authorized to perform.

CSRF attacks exploit the trust a web application has in the user's browser. Unlike XSS, which exploits the user's trust in a website, CSRF exploits the website's trust in the user's browser. The attack works because the browser automatically attaches cookies, HTTP authentication credentials, and client-side SSL certificates to any request sent to the target domain.

Modern CSRF protection employs multiple strategies: the synchronizer token pattern, where a unique, unpredictable token is embedded in forms and validated server-side; the double-submit cookie pattern, where a random value is sent as both a cookie and a request parameter; the SameSite cookie attribute, which prevents browsers from sending cookies with cross-origin requests; and verifying the Origin and Referer headers. Token-based protection remains the gold standard, while SameSite cookies provide an important defense-in-depth layer.

Prompt Snippet

Implement CSRF protection using the synchronizer token pattern: generate a cryptographically random token per session using crypto.randomBytes(32), embed it in a hidden form field and store it server-side in the session. Validate the token on every state-changing request (POST/PUT/DELETE/PATCH). For SPA architectures, use the double-submit cookie pattern with a custom X-CSRF-Token header combined with SameSite=Strict cookies. Configure your framework's CSRF middleware (e.g., csurf for Express, @csrf-csrf/express) and ensure all AJAX requests include the token via an Axios/fetch interceptor.

Tags

csrfsession-securitytoken-validationcookies