CSRF is a web attack that tricks authenticated users into submitting unintended requests, allowing attackers to perform unauthorized actions like changing passwords or transferring funds.
CSRF (Cross-Site Request Forgery) is an attack that forces authenticated users to execute unwanted actions on a web application. When a victim visits a malicious page, it automatically sends forged requests using the victim's active session cookies, performing state-changing operations without the user's knowledge or consent.
An attacker crafts a malicious page containing hidden forms or image tags that target a vulnerable application. When an authenticated victim visits this page, their browser automatically includes session cookies with the forged request. The server cannot distinguish the forged request from a legitimate one, executing the action.
CSRF can enable attackers to change user passwords, modify email addresses, transfer funds, make purchases, change account settings, escalate privileges, or perform any state-changing action the victim is authorized to do. Impact depends on the victim's role and the application's functionality.
Anti-CSRF tokens are unique, unpredictable values tied to user sessions that must be included in state-changing requests. Since attackers cannot read the token from the target domain due to same-origin policy, they cannot forge valid requests. The server validates the token before processing each request.
The SameSite cookie attribute instructs browsers to restrict cookie transmission in cross-origin requests. Setting SameSite=Strict or SameSite=Lax prevents cookies from being sent with cross-site requests, providing defense-in-depth against CSRF attacks alongside token-based protections.
Traditional CSRF primarily affects cookie-authenticated web applications. APIs using bearer tokens in Authorization headers are generally immune since browsers do not automatically attach these headers cross-origin. However, APIs relying on cookie authentication remain vulnerable and require CSRF protections.
CSRF exploits the server's trust in the user's browser by forging requests with valid session cookies. XSS exploits the user's trust in the server by injecting malicious scripts. XSS can bypass CSRF defenses by reading anti-CSRF tokens from the page, making XSS the more severe vulnerability.
Modern prevention combines synchronizer token patterns or double-submit cookies with SameSite cookie attributes set to Lax or Strict. Additional measures include requiring re-authentication for sensitive operations, validating Origin and Referer headers, using custom request headers for AJAX calls, and implementing CAPTCHA for critical actions.