The attack mechanism and browser trust
Cross-Site Request Forgery (CSRF) exploits a browser's automatic credential sending. A user logs into their bank at bank.com, and the browser stores a session cookie. The user then visits attacker.com in another tab. The attacker's site contains a form or image tag pointing to bank.com/transfer?amount=1000&to=attacker (a state-changing request). The browser, seeing a request to bank.com, automatically includes the session cookie. The bank receives the request with valid credentials and thinks the user initiated the transfer. The attacker has forged a request on the user's behalf.
Defenses through token validation
The primary defense is a CSRF token: a per-session, unpredictable value that the server requires for state-changing requests. The form or API request includes the token, and only the legitimate site (not the attacker's site) can read it from the page source. The attacker's site cannot guess or retrieve the token, so its forged request fails. Tokens are single-use or long-lived per-session. Same-site cookies (Set-Cookie: SameSite=Strict) prevent the browser from including cookies on cross-site requests, but browser support varies. Checking the Referer header (which origin initiated the request) helps, but is less reliable than tokens.
Vulnerability in modern applications
APIs that accept CORS (cross-origin requests) or rely on Authorization headers rather than cookies are less vulnerable, since browsers do not auto-include custom headers. APIs with state-changing GET requests (instead of POST) are more vulnerable: any image or link tag can trigger them. Session fixation (attacker forces the user to use the attacker's session token) is a related attack. Proper mitigation requires CSRF tokens on all forms, SameSite cookie attributes, and POST/PUT/DELETE for mutations.