How CSRF tricks a victim's browser into making unwanted requests and how to prevent it.
Cross-Site Request Forgery (CSRF or XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. A successful CSRF attack can force the user to perform state-changing requests like transferring funds, changing their email address, or purchasing an item. The attack works by leveraging the trust that a web application has in a user's browser. If a user is logged into `mybank.com`, and an attacker tricks them into visiting a malicious website, that website can contain hidden code (e.g., in an image tag) that sends a request to `mybank.com`. Since the user is already authenticated with `mybank.com`, their browser will automatically include their session cookie with the request. From the bank's perspective, this appears to be a legitimate request from the authenticated user, so it will process the request, for example, to transfer money. The victim would have no knowledge of this happening in the background. The most common and robust method to prevent CSRF is the Synchronyzer Token Pattern. When a user visits a page with a form, the server generates a unique, random, unpredictable token and includes it as a hidden field in the form. When the user submits the form, this token is sent back to the server. The server then validates that the token received matches the one it generated for that user's session. Since the attacker's malicious site cannot know the value of this secret token, any forged request it sends will be missing the valid token and will be rejected by the server.