HIGH Authentication

Cross Site Request Forgery in APIs

What is Cross Site Request Forgery?

Cross Site Request Forgery (CSRF) is a web security vulnerability that forces authenticated users to execute unwanted actions on a web application where they're currently logged in. In API contexts, CSRF occurs when an attacker crafts a malicious request that, when processed by the victim's browser, appears to come from a legitimate user and carries their authentication context.

The attack exploits the trust that a web application has in a user's browser. When a user is authenticated to an API, their browser automatically includes session cookies, authorization headers, or other credentials with every request to that domain. An attacker can create a malicious website or email that makes requests to the target API using the victim's credentials without their knowledge.

CSRF attacks work because browsers automatically send credentials with requests to the same-origin domain. If a banking API endpoint at api.bank.com processes fund transfers without proper CSRF protection, an attacker could create a page that, when visited by a logged-in user, automatically sends a request to transfer money from the victim's account to the attacker's account.

The fundamental issue is that the API trusts any request coming from an authenticated user's browser, regardless of whether the user intended to make that request. This trust relationship between the API and the user's browser is what CSRF exploits.

How Cross Site Request Forgery Affects APIs

CSRF in APIs can lead to severe consequences depending on the functionality exposed. Attackers can exploit state-changing operations that don't require additional user interaction beyond being authenticated. Common targets include:

  • Financial transactions: Unauthorized money transfers, stock trades, or payment processing
  • Account modifications: Changing email addresses, passwords, or security questions
  • Data manipulation: Deleting records, modifying personal information, or posting content
  • Privilege escalation: Promoting user accounts or granting admin access

A classic example involves a social media API that allows users to post status updates. An attacker could create a malicious page that, when loaded by a victim, automatically sends a POST request to the API's status update endpoint with a message promoting the attacker's content or spreading misinformation.

More sophisticated attacks target APIs that don't properly validate the origin of requests. Even APIs that use token-based authentication can be vulnerable if the tokens are stored in cookies and automatically included with cross-origin requests. The attack becomes particularly dangerous when combined with social engineering—attackers can embed malicious requests in emails, forum posts, or compromised websites.

The impact extends beyond immediate data loss or unauthorized actions. CSRF can be used as part of larger attack chains, such as bypassing CSRF protection by combining it with other vulnerabilities like XSS or clickjacking to create more convincing attack vectors.

How to Detect Cross Site Request Forgery

Detecting CSRF vulnerabilities requires examining how APIs handle authentication and request validation. The key indicators are:

  • Cookie-based authentication without anti-CSRF tokens: APIs that rely solely on session cookies for authentication are vulnerable if they don't implement CSRF tokens or same-site cookie policies
  • Missing SameSite cookie attributes: Cookies without SameSite restrictions can be sent in cross-site requests
  • State-changing operations without verification: POST, PUT, DELETE, and PATCH endpoints that don't validate request origin
  • Missing or predictable anti-CSRF tokens: If tokens are used but are predictable or not properly validated

middleBrick scans for CSRF vulnerabilities by testing unauthenticated endpoints for common CSRF patterns. The scanner checks whether APIs accept requests that appear to come from authenticated users without proper anti-CSRF mechanisms. It examines cookie configurations, tests for missing SameSite attributes, and evaluates whether state-changing operations can be triggered through cross-site requests.

The scanner also analyzes OpenAPI specifications to identify endpoints that perform state-changing operations and cross-references these with runtime findings. This helps prioritize which endpoints require the most urgent protection since they're most likely to be targeted by CSRF attacks.

middleBrick's black-box scanning approach tests the actual attack surface without requiring credentials or configuration. The scanner sends test requests with various authentication scenarios to determine if CSRF protections are properly implemented, providing actionable findings about which endpoints are vulnerable and what specific protections are missing.

Prevention & Remediation

Preventing CSRF requires implementing multiple layers of defense. The most effective approach combines several techniques:

SameSite Cookie Attribute: Set SameSite=Lax or SameSite=Strict on all authentication cookies. Strict provides the strongest protection by preventing cookies from being sent in cross-site requests entirely:

Set-Cookie: session_id=abc123; SameSite=Strict; Secure; HttpOnly

Anti-CSRF Tokens: Include a unique, unpredictable token in all state-changing forms and API requests. The token should be tied to the user's session and validated on the server:

// Generate token on server (Node.js example)function generateCSRFToken(req) {  return crypto.randomBytes(32).toString('hex');}// Validate token on serverapp.post('/api/update-profile', (req, res) => {  const csrfToken = req.headers['x-csrf-token'];  if (!csrfToken || csrfToken !== req.session.csrfToken) {    return res.status(403).json({ error: 'CSRF token mismatch' });  }  // Process request});

Double Submit Cookie Pattern: Send the anti-CSRF token both as a cookie and as a request header. The server verifies that both values match, ensuring the request originated from your site:

// Client-side JavaScriptdocument.addEventListener('DOMContentLoaded', () => {  const csrfToken = getCookie('csrf_token');  fetch('/api/protected-endpoint', {    method: 'POST',    headers: {      'X-CSRF-Token': csrfToken    },    credentials: 'include'  });});

Custom Request Headers: Require custom headers like X-Requested-With or X-API-Key for state-changing operations. Since browsers don't allow setting custom headers in cross-site requests initiated by simple links or form submissions:

app.post('/api/transfer', (req, res) => {  if (!req.headers['x-requested-with']) {    return res.status(403).json({ error: 'Missing required header' });  }  // Process transfer});

SameSite cookies with Lax mode provides a good balance for APIs that need to handle cross-site navigation while still protecting against CSRF. This allows GET requests to work across sites (useful for OAuth flows) while blocking state-changing requests.

Real-World Impact

CSRF vulnerabilities have led to significant real-world breaches. In 2007, a CSRF vulnerability in Netflix allowed attackers to add any movie to a victim's DVD queue without their knowledge. More recently, in 2020, a critical CSRF flaw in a major financial services API allowed attackers to initiate wire transfers from authenticated user accounts.

The vulnerability CVE-2020-13942 in Apache Unomi (an open-source customer data platform) demonstrated how CSRF could be exploited to execute remote code. The flaw allowed unauthenticated attackers to perform administrative actions through CSRF attacks, potentially leading to complete system compromise.

APIs are particularly vulnerable when they're designed for single-page applications or mobile clients that don't implement traditional CSRF protections. Many developers assume that token-based authentication makes CSRF impossible, but if those tokens are stored in cookies or local storage accessible to JavaScript, the vulnerability remains.

The financial impact of CSRF attacks can be substantial. Beyond direct monetary losses from unauthorized transactions, companies face regulatory fines, legal costs, and reputational damage. PCI-DSS compliance requires protection against CSRF for any API handling payment card data, making this a critical security requirement for e-commerce and financial services.

Frequently Asked Questions

Can't I just use JWT tokens in HTTP headers to prevent CSRF?
Not entirely. While JWT tokens in Authorization headers are more secure than cookies, they're not a complete solution. If the JWT is stored in local storage or session storage, it's still vulnerable to XSS attacks that can read the token and make API requests. Additionally, many applications store JWTs in cookies for convenience, which reintroduces CSRF risk. The most secure approach combines proper token storage with anti-CSRF tokens or SameSite cookies.
How does SameSite=Lax differ from SameSite=Strict for CSRF protection?
SameSite=Strict blocks all cross-site cookie sending, providing maximum CSRF protection but breaking legitimate cross-site workflows like OAuth login flows. SameSite=Lax allows cookies to be sent with top-level navigations (like clicking a link to your site) but blocks them for cross-site POST requests. For most APIs, Strict is ideal for sensitive operations, while Lax works well for general use cases where some cross-site functionality is needed.
Does middleBrick detect if my API is vulnerable to CSRF?
Yes, middleBrick's black-box scanning tests your API endpoints for common CSRF vulnerabilities. The scanner checks cookie configurations for missing SameSite attributes, tests whether state-changing operations can be triggered through cross-site requests, and evaluates anti-CSRF token implementations. middleBrick provides specific findings about which endpoints are vulnerable and what protections are missing, along with remediation guidance to help you fix the issues.