| |

Web Security 06 🛡️ Cross-Site Request Forgery (CSRF) — Mitigating forged requests with SameSite cookies, Fetch Metadata, and anti-CSRF tokens

⏱️ Estimated read: 9 min | |

Cross-Site Request Forgery (CSRF) is an attack that exploits the way browsers handle authentication. When a user logs into a web application, the application typically sets a session cookie. The browser, by design, automatically attaches these cookies to every subsequent request made to that specific domain. A CSRF attack leverages this “ambient authority,” tricking an authenticated user’s browser into sending an HTTP request to the target site without the user’s consent or knowledge.

Because the request carries the user’s session cookies, the server cannot distinguish between a legitimate request initiated by the user and a forged one initiated by a malicious third-party site. This chapter covers the mechanics of how these requests are forged and the multi-layered defense strategies necessary to prevent them. We will explore the synchronizer token pattern, the implementation of SameSite cookie attributes, and the use of browser-native Fetch Metadata headers.

Key point: CSRF attacks work because browsers automatically include credentials like session cookies in cross-site requests; the fundamental defense requires ensuring that state-changing requests originate from the application’s own origin, verified by cryptographic tokens or browser-enforced cookie policies.


Why X exists

1. The ambient authority problem.

Browsers are designed to be helpful. When a user interacts with a site, the browser automatically attaches all cookies associated with that domain to outgoing requests. This convenience is the root cause of CSRF, as it means authentication is “ambient”—always available to the browser without the user explicitly re-authorizing every single request.

2. Lack of intent verification in HTTP.

Standard HTTP methods (like POST or PUT) do not inherently verify that the user intended to perform the action. If a server receives a request with a valid session cookie, it assumes the user is logged in and authorized, providing no secondary proof of intent by default.

3. The confused deputy scenario.

The server acts as a “confused deputy.” It has the power to perform sensitive actions (like changing a password), and it trusts the identity of the requester (the session cookie). When a malicious site submits a form to the server on the user’s behalf, the server is tricked into fulfilling the request for the wrong reasons.

4. Cross-site scripting interaction.

While CSRF is distinct from XSS, it often relies on similar vectors. An attacker might host a malicious page that embeds an invisible <iframe> or a hidden <form> that auto-submits, using the victim’s own browser as the attack vector to hit the target server.

5. Need for defense-in-depth.

No single solution is a silver bullet. Anti-CSRF tokens provide strong protection but require implementation effort. SameSite cookies provide browser-level protection but depend on browser support. Fetch Metadata provides a robust, modern way to verify request origin. Combining these ensures that if one layer fails, others maintain security.


a. Anti-CSRF tokens (Synchronizer Token Pattern)

The Synchronizer Token Pattern is the gold standard for CSRF prevention. The server generates a cryptographically strong, random, and unique token for the user’s session. This token is embedded into every state-changing HTML form or included as a header in AJAX requests. When the server receives the request, it verifies that the token submitted matches the token stored in the user’s session.

// Server generates and stores the token
const csrfToken = crypto.randomBytes(32).toString('hex');
req.session.csrfToken = csrfToken;

// The token is rendered into the HTML form
// <input type="hidden" name="csrf_token" value="<%= csrfToken %>">

If the malicious site attempts to forge the request, it cannot read the token from the legitimate site (due to the Same-Origin Policy). Therefore, the attacker cannot include the correct token in their forged request, and the server will reject it.

// Server middleware validates the token
function validateCsrf(req, res, next) {
  const userToken = req.body.csrf_token || req.headers['x-csrf-token'];
  if (userToken !== req.session.csrfToken) {
    return res.status(403).send('Invalid CSRF Token');
  }
  next();
}

This ensures that the request originated from a page the server generated, rather than an arbitrary third-party site.


b. SameSite cookie attributes

SameSite is a cookie attribute that instructs the browser whether to send cookies with cross-site requests. By configuring this attribute correctly, you can effectively neutralize CSRF for many standard workflows.

  • Strict: The cookie is only sent if the request originates from the same site where the cookie was set. This is the most secure option but may break user experience if users click links from external sites to navigate to your app.
  • Lax: The default in modern browsers. The cookie is not sent on cross-site sub-requests (like images or frames) but is sent when the user navigates to the origin site via a standard GET link.
  • None: The cookie is sent with all requests, including cross-site ones. This requires the Secure flag.
// Setting a cookie with SameSite=Lax
res.cookie('session_id', 'xyz123', {
  httpOnly: true,
  secure: true, // Required for SameSite=None
  sameSite: 'lax' // Prevents CSRF on standard form submissions
});

While SameSite=Lax is an excellent defense-in-depth layer, it should not be the only line of defense for critical state-changing operations like password changes or financial transactions.


c. Fetch Metadata and Origin validation

Fetch Metadata Request Headers are a set of HTTP request headers (Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest) that browsers automatically set. They allow the server to understand why a request is being made and where it is coming from, without needing a stateful token.

Sec-Fetch-Site is particularly useful. It tells the server if the request is same-origin, same-site, cross-site, or none.

// Middleware to verify Fetch Metadata
function verifyFetchMetadata(req, res, next) {
  const site = req.headers['sec-fetch-site'];

  // Block cross-site requests for state-changing methods
  if (req.method !== 'GET' && site === 'cross-site') {
    return res.status(403).send('Forbidden: CSRF check failed');
  }
  next();
}

By validating that the Sec-Fetch-Site is not cross-site for sensitive operations, you effectively block forged requests from external domains. This serves as a powerful “fail-safe” mechanism alongside standard token validation.


Complete Example Session

// ============================================
// PART 1: GENERATING THE TOKEN
// ============================================
const generateToken = (req) => {
  const token = crypto.randomBytes(32).toString('hex');
  req.session.csrfToken = token;
  return token;
};

// ============================================
// PART 2: THE FORM TEMPLATE
// ============================================
// The view engine injects the token
// <form action="/update-email" method="POST">
//   <input type="hidden" name="_csrf" value="<%= req.session.csrfToken %>">
//   <button type="submit">Update</button>
// </form>

// ============================================
// PART 3: SERVER VALIDATION
// ============================================
app.post('/update-email', (req, res) => {
  if (req.body._csrf !== req.session.csrfToken) {
    return res.status(403).send('CSRF Detected');
  }
  // Process...
});

// ============================================
// PART 4: SAME-SITE COOKIE CONFIG
// ============================================
app.use(session({
  cookie: { sameSite: 'lax', secure: true, httpOnly: true }
}));

// ============================================
// PART 5: FETCH METADATA CHECK
// ============================================
app.use((req, res, next) => {
  if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
    const site = req.get('sec-fetch-site');
    if (site === 'cross-site') return res.sendStatus(403);
  }
  next();
});

// ============================================
// PART 6: ORIGIN VALIDATION
// ============================================
const allowedOrigins = ['https://myapp.com'];
app.use((req, res, next) => {
  const origin = req.get('origin');
  if (origin && !allowedOrigins.includes(origin)) {
    return res.sendStatus(403);
  }
  next();
});

// ============================================
// PART 7: EXEMPTIONS (GET REQUESTS)
// ============================================
// GET requests should never be state-changing
// They do not need CSRF tokens
app.get('/dashboard', (req, res) => { /* display */ });

// ============================================
// PART 8: AJAX HEADER PATTERN
// ============================================
// Client sets a custom header
// fetch('/api', { headers: { 'X-CSRF-TOKEN': token } });

// ============================================
// PART 9: AJAX SERVER CHECK
// ============================================
app.use((req, res, next) => {
  const header = req.get('x-csrf-token');
  if (header !== req.session.csrfToken) return res.sendStatus(403);
  next();
});

// ============================================
// PART 10: SECURE COOKIE FLAG
// ============================================
// Ensure the cookie is only sent over HTTPS
res.cookie('token', '...', { secure: true });

This session demonstrates a multi-layered approach, combining tokens, browser-native cookie attributes, and request header validation to prevent CSRF.


Quick Reference

CSRF Defense Layers

StrategyMechanism
Anti-CSRF TokenServer-side validation
SameSite CookiesBrowser-level constraint
Fetch MetadataHeader validation
Origin HeaderRequest source check

SameSite Attributes

AttributeBehavior
StrictNo cross-site cookies
LaxCookies on top-level GET
NoneCookies everywhere

Fetch Metadata Headers

HeaderMeaning
Sec-Fetch-SiteOrigin of the request
Sec-Fetch-ModeNavigation mode
Sec-Fetch-DestDestination (iframe/img/etc)

Best Practices

✅ Do This:

// Use CSRF tokens for all state-changing requests       // ✅
res.cookie('sess', val, { sameSite: 'lax', secure: true }); // ✅
// Verify the Origin header in your middleware          // ✅
// Use custom headers for AJAX requests                 // ✅
// Keep GET requests idempotent (read-only)             // ✅
// Rotate tokens on session regeneration                // ✅

❌ Don’t Do This:

// Don't use GET for state changes                     // ❌
// Don't rely solely on SameSite=None                  // ❌
// Don't leak CSRF tokens in URLs                      // ❌
// Don't allow cross-site POST without checks           // ❌
// Don't trust the Referer header alone                // ❌

Common Pitfalls

PitfallWhy It HappensFix
GET changes stateHTTP standards ignoredUse POST/PUT/DELETE
SameSite=NoneUsed without SecureAdd secure: true
Token in URLDeveloper convenienceUse request body/header
CORS misconfigOverly permissive originsStrict origin whitelist
Missing TokenFrontend integration failureAdd hidden field/header

Real-World Examples

1. Hidden input token

<input type="hidden" name="csrf" value="abc12345">

2. AJAX custom header

xhr.setRequestHeader('X-CSRF-TOKEN', token);

3. SameSite cookie config

res.cookie('sid', '123', { sameSite: 'lax' });

4. Origin verification

if (req.get('origin') !== 'https://app.com') abort();

5. Fetch Metadata check

if (req.get('sec-fetch-site') === 'cross-site') abort();

6. Idempotent GET

// Never allow form submission here
app.get('/delete', ...);

7. Session regeneration

req.session.regenerate(() => { token = ... });

8. Secure flag

res.cookie('token', val, { secure: true });

9. HttpOnly flag

res.cookie('token', val, { httpOnly: true });

10. Multi-layer defense

middleware(validateToken, validateOrigin);

Visual

The CSRF Flow

┌──────────────────────────────────────────────┐
│  ATTACKER SITE        VICTIM BROWSER         │
│  <form action=        sends POST + cookies   │
│   target.com>     ─►  (Ambient Auth)         │
│         │                    │               │
│         └────────────┐       │               │
│                      │       ▼               │
│                TARGET SERVER (Vulnerable)    │
│                processes request as user     │
└──────────────────────────────────────────────┘

Cookie SameSite Logic

┌──────────────────────────────────────────────┐
│  BROWSER REQUEST                             │
│                                              │
│  SAME-SITE    ─► Send cookies (Allowed)      │
│  CROSS-SITE   ─► Check SameSite policy       │
│                                              │
│  Policy None  ─► Send cookies                │
│  Policy Lax   ─► Send only on top-level GET  │
│  Policy Strict─► Never send cookies          │
└──────────────────────────────────────────────┘

Verification Layer

┌──────────────────────────────────────────────┐
│  INCOMING REQUEST                            │
│  1. Check Method (GET = Skip)                │
│  2. Check Origin Header                      │
│  3. Check Fetch Metadata (Sec-Fetch)         │
│  4. Check CSRF Token (Body/Header)           │
│  5. Accept Request                           │
└──────────────────────────────────────────────┘

Summary

ItemValue
Attack VectorAmbient Authority (Cookies)
Mitigation 1Anti-CSRF Synchronizer Tokens
Mitigation 2SameSite Cookies (Lax/Strict)
Mitigation 3Fetch Metadata (Sec-Fetch-Site)
Mitigation 4Origin/Referer Validation
HTTP MethodsUse POST/PUT/DELETE for changes
Cookie FlagAlways use Secure + HttpOnly

Key takeaways:

  • Ambient authority is the cause. Browser automatic cookie attachment makes CSRF possible; mitigation focuses on explicit validation.
  • Synchronizer tokens are essential. Including a unique, per-session token in state-changing requests is the most robust defense.
  • Configure SameSite properly. Setting SameSite=Lax or Strict adds a vital layer of browser-level protection.
  • Validate origins and metadata. Checking Origin and Sec-Fetch-Site headers allows servers to drop requests originating from unauthorized domains.
  • GET requests must be read-only. Never perform state changes on GET requests, as they are excluded from many CSRF protections.
  • Defense in depth. Use multiple strategies simultaneously to ensure that if one fails, others protect the application.

Remember: CSRF exploits the gap between the server’s trust in a session cookie and the request’s actual intent. By enforcing strict cookie attributes, validating the origin of every state-changing request, and requiring an unforgeable token, you remove the attacker’s ability to “confuse the deputy” and execute unauthorized actions.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!