CSRF & SameSite

Vibe Prompt

"Explore csrf & samesite with examples and prevention techniques."

Key Concepts

  • Core principles and attack vectors
  • Detection and exploitation techniques
  • Prevention and mitigation strategies
  • Real-world examples and case studies

Practice Exercise

๐Ÿ’ก Practice: Ask AI to help you create a vulnerable app and test these protections.

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials

What Is CSRF?

Cross-Site Request Forgery (CSRF) tricks an authenticated user into executing unwanted actions on a web application where they are logged in.

How CSRF Works

1. User logs into bank.com (gets session cookie)
2. User visits evil.com (another tab)
3. evil.com contains: <img src="https://bank.com/transfer?amount=1000&to=attacker">
4. Browser automatically sends the cookie along with the request
5. Bank processes the transfer โ€” thinks it's from the legitimate user!

Why Browser Sends Cookies

| Cookie Attribute | Sent Cross-Site? | |-----------------|------------------| | Default (no SameSite) | โœ… Yes | | SameSite=Lax | โœ… Yes (top-level GET) | | SameSite=Strict | โŒ No | | SameSite=None + Secure | โœ… Yes (HTTPS only) |

CSRF Prevention Strategies

1. SameSite Cookies (Modern Solution)

// Next.js: Set SameSite cookie attribute
// In API response:
res.setHeader('Set-Cookie', [
  `session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=86400`
]);

| SameSite Value | Protection | UX Impact | |----------------|------------|-----------| | Strict | Maximum | Breaks links from external sites | | Lax | Good for most | Allows top-level GET navigations | | None | None | Requires Secure + explicit CSRF token |

2. CSRF Tokens (Traditional Solution)

// Server generates and validates CSRF token
import { randomBytes } from 'crypto';

// Generate token
function generateCsrfToken(): string {
  return randomBytes(32).toString('hex');
}

// Store in session (not accessible via JS)
// Return in response or embed in form

// Client: Send token with state-changing requests
async function submitForm(formData: FormData) {
  const response = await fetch('/api/transfer', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': getCsrfToken(),  // From meta tag or cookie
    },
    body: JSON.stringify({ amount: 100, to: 'alice' }),
  });
}

// Server: Validate token
app.post('/api/transfer', (req, res) => {
  const token = req.headers['x-csrf-token'];
  if (!token || token !== req.session.csrfToken) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }
  // Process transfer...
});

3. Custom Request Headers

// APIs protected by custom headers (not sent cross-origin)
fetch('/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Requested-By': 'my-app',  // Custom header
  },
});

// Server: verify custom header exists
app.post('/api/data', (req, res) => {
  if (!req.headers['x-requested-by']) {
    return res.status(403).json({ error: 'CSRF check failed' });
  }
});

4. Origin / Referer Header Check

app.post('/api/transfer', (req, res) => {
  const origin = req.headers['origin'];
  const referer = req.headers['referer'];
  
  const allowedOrigins = ['https://bank.com'];
  
  if ((origin && !allowedOrigins.includes(origin)) ||
      (referer && !allowedOrigins.includes(new URL(referer).origin))) {
    return res.status(403).json({ error: 'Invalid origin' });
  }
});

CSRF Prevention Comparison

| Method | Effort | Protection Level | Breaks Links? | |--------|--------|-----------------|---------------| | SameSite=Lax | Low | Good | โŒ No | | SameSite=Strict | Low | Maximum | โœ… Yes | | CSRF Token | Medium | Maximum | โŒ No | | Custom Header | Medium | Good | โŒ No | | Origin Check | Low | Moderate | โŒ No |

Summary

CSRF tricks authenticated users into performing unwanted actions. Prevention combines SameSite cookies, CSRF tokens, custom headers, and origin validation.

Key takeaways: | CSRF: attacker uses the victim's session cookie to make unauthorized requests | | SameSite=Lax: prevents most CSRF without breaking user experience | | SameSite=Strict: maximum protection but breaks external links | | CSRF token: secret token validated on every state-changing request | | Custom header (X-Requested-By): not sent cross-origin by browsers | | Origin/Referer check: verify the request came from your domain | | Use SameSite as baseline + CSRF tokens for sensitive actions (transfers) |

What's Next: Secure API

The next chapter covers building a fully secured API.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!