What Is CSRF? Cross-Site Request Forgery Explained
Cross-Site Request Forgery (CSRF) is an attack where a malicious website tricks an authenticated user's browser into making an unintended request to another site where they are logged in. Because the browser automatically includes session cookies, the server cannot distinguish the legitimate request from the forged one.
How CSRF Works
Alice is logged into bank.com. She visits malicious.com, which contains: <img src='https://bank.com/transfer?to=attacker&amount=1000'>. The browser loads the image URL, automatically sending Alice's bank.com session cookie. The bank executes the transfer. CSRF is only possible when the server uses cookies for authentication and the cookie is sent for cross-origin requests.
CSRF Tokens
The classic defence is a CSRF token: a unique, secret, per-session random value embedded in every state-changing form. The server verifies the token matches. An attacker on a different origin cannot read the token (same-origin policy), so they cannot forge valid requests. Synchroniser Pattern: server generates and validates the token. Double Submit Cookie: token in both a cookie and a request parameter.
SameSite Cookies
The SameSite cookie attribute is now the primary CSRF defence. SameSite=Strict: cookie not sent with any cross-site request — breaks some OAuth flows. SameSite=Lax: cookie sent only for top-level navigation GET requests (clicking links). SameSite=None; Secure: always sends — opt-in for third-party use cases. Modern browsers default to Lax, making CSRF much harder without any code changes.