Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user's browser into unknowingly submitting a malicious request to a web application where the user is currently logged in.
Definition
Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user's browser into unknowingly submitting a malicious request to a web application where the user is currently logged in.
Overview
CSRF exploits the fact that browsers automatically attach cookies (including session cookies) to any request sent to a site, regardless of where that request originated. If a victim is logged into a banking site and visits a malicious page containing a hidden form that auto-submits to the bank's "transfer funds" endpoint, the browser will include the victim's valid session cookie, and the bank server has no way to tell the request wasn't intentional — unless it has CSRF protections in place. Common defenses include CSRF tokens (a random, unpredictable value embedded in forms and validated server-side on submission), the SameSite cookie attribute (which restricts when cookies are sent on cross-site requests), and re-authentication for sensitive actions. CSRF is distinct from Cross-Site Scripting (XSS) — CSRF forges a request using the victim's existing session, while XSS injects and runs code in the victim's browser — but the two are often used together to escalate an attack. API-heavy applications need to think carefully about CSRF alongside broader Authentication and Authorization design, a topic covered in the API Security course.
Key Concepts
- Exploits automatic cookie/session inclusion in cross-origin requests
- Requires the victim to be authenticated and tricked into visiting a malicious page
- Mitigated with anti-CSRF tokens validated on every state-changing request
- SameSite cookie attribute limits when cookies are sent cross-site
- Distinct from but often paired with XSS for a stronger attack
- Primarily affects state-changing operations (POST/PUT/DELETE), not simple reads