What is CSRF?
CSRF (Cross-Site Request Forgery) is a web security attack where a malicious website tricks a user's browser into making an unwanted request to another site where the user is authenticated, potentially performing actions without the user's consent.
How Does CSRF Work?
A CSRF attack exploits the fact that browsers automatically include cookies (including authentication cookies) with every request to a domain. An attacker creates a page that contains a hidden form or image tag pointing to the target site. When an authenticated user visits the attacker's page, their browser unknowingly sends a request to the target site with valid session credentials, potentially changing account settings, transferring funds, or performing other privileged actions.
The primary defense against CSRF is the synchronizer token pattern: the server generates a unique, unpredictable token for each session or form and requires it to be included in every state-changing request. Since the attacker cannot read or predict this token, forged requests will be rejected. Modern frameworks include built-in CSRF protection, and the SameSite cookie attribute provides an additional browser-level defense by controlling when cookies are sent with cross-site requests.