CSRF in REST APIs
You'll learn: Why token-based authentication in REST APIs reduces CSRF risk, and when you still need protection.
The Stateless API Advantage
REST APIs are typically designed to be stateless, meaning each request contains all the information needed to authenticate and process it—no server-side session cookies. This architectural choice dramatically reduces CSRF risk.
Remember that CSRF attacks work by tricking your browser into automatically sending stored credentials (usually session cookies) to a target site. If an API relies on bearer tokens passed in HTTP headers (like Authorization: Bearer <token>), the browser won't automatically include these with cross-origin requests. A malicious site can't access tokens stored in JavaScript variables or localStorage to include them in forged requests.
When REST APIs Are Still Vulnerable
However, not all REST APIs are immune:
-
Cookie-based authentication: If your "REST" API still uses session cookies for authentication (not truly stateless), CSRF attacks work exactly as with traditional web apps. You need CSRF tokens or SameSite cookies.
-
Browser-based clients: When your API serves a single-page application (SPA) that stores tokens in cookies for convenience, you've reintroduced CSRF risk.
-
GET requests with side effects: Even with token auth, if your API violates REST principles by allowing state changes via GET (which browsers can trigger easily), you've created an attack surface.
Analogy: It's like having a secure keycard system (token auth) instead of a doorman who recognizes your face (session cookies). A stranger can't use your keycard if they don't physically have it, but if you tape your keycard to your forehead (cookies), that stranger can walk you through the door.
Key Takeaway: Token-based authentication in headers provides natural CSRF protection for REST APIs, but any use of cookies for authentication or deviation from stateless design requires traditional CSRF defenses.