The Cross-Site Trust Exploit
Cross-Site Request Forgery (CSRF) is an attack that forces an authenticated user browser to execute actions on a web application where they are logged in.
- ◆The Vulnerability: Browsers append session cookies automatically to all HTTP requests sent to a domain, even if the request originates from a malicious site.
- ◆The Target: Actions like changing passwords, transferring money, or updating email accounts.
Mitigating CSRF requires validating that request originations are legitimate.
Security Rule: Never trust a request simply because it contains valid session cookies. You must validate an independent anti-forgery token.
Anti-Forgery Token Mechanics (Synchronizer Token Pattern)
The most common way to block CSRF is the Synchronizer Token Pattern:
- 1.The server generates a cryptographically secure, random token and associates it with the user's session.
- 2.The server inserts this token as a hidden field inside all HTML forms.
- 3.On submission, the server compares the form parameter token with the session token. If they mismatch, the request is rejected.
| Mitigation Pattern | Verification Source | State Storage |
|---|---|---|
| Synchronizer Token | Session storage | State stored on server. |
| Double-Submit Cookie | Cookie vs HTTP Header | Stateless (favored in APIs). |
Implementing Stateless Double-Submit Cookies
For stateless APIs, the server writes a random token to a cookie. The client reads this cookie and copies the token value into a custom HTTP request header (e.g., X-XSRF-TOKEN). The server validates that both tokens match:
// Client-side CSRF token placement in jQuery AJAX
const csrfToken = readCookie("CSRF-TOKEN");
$.ajax({
url: "/api/billing/charge",
type: "POST",
headers: {
"X-XSRF-TOKEN": csrfToken
}
});By enforcing anti-forgery headers on all state-changing operations (POST, PUT, DELETE), you protect your application against CSRF hijacks.