CSRF

Security

Overview

CSRF (Cross-Site Request Forgery) is an attack where a logged-in user visits a malicious site that uses the user's auth cookie to send a state-changing request to the target site without the user's knowledge.

The core principle exploits the fact that the browser automatically attaches the target site's cookie to requests going there.

Details

For example, while a user is logged into their bank, opening the attacker's page can auto-fire a hidden form/image/script doing `POST https://bank.com/transfer`, and the browser includes the bank cookie. To the bank server it's indistinguishable from a legitimate request, so a transfer may execute. This works because the Same-Origin Policy only blocks reading the response, not sending the request — the side effect happens even though the response can't be read.

Defenses are layered: (1) `SameSite=Lax/Strict` cookies, which stop cookies from riding cross-site requests, are today's most fundamental mitigation; (2) CSRF tokens (synchronizer-token pattern): the server embeds an unpredictable token in the form/header and validates it, and an attacker who can't read the response can't know it; (3) use only non-safe methods (POST, etc.) for state changes and never cause side effects via GET. Note: APIs that use only a Bearer token in the `Authorization` header (not cookies) are inherently less susceptible, since browsers don't auto-attach that header. Conversely, if XSS exists it can defeat any CSRF defense, so blocking XSS must come first.

Related types