Owasp csrf protection

From Intense-Visions/harness-engineering · View interactive version

Owasp csrf protection is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Prevent cross-site request forgery by validating request origin and requiring unpredictable tokens for state-changing operations

How to use this skill

Skill file

OWASP CSRF Protection

Prevent cross-site request forgery by validating request origin and requiring unpredictable tokens for state-changing operations

When to Use

Instructions

SameSite Cookies — First Line of Defense

Modern browsers support SameSite=Strict or SameSite=Lax which blocks CSRF for most cases:

res.cookie('session_id', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict', // cross-site requests never send this cookie
  maxAge: 15 * 60 * 1000,
});

Synchronizer Token Pattern

For forms and traditional server-rendered pages:

import csrf from 'csurf';

// Express — csurf middleware
const csrfProtection = csrf({ cookie: { sameSite: 'strict', httpOnly: true } });

app.get('/form', csrfProtection, (req, res) => {
  // Pass token to the template
  res.render('form', { csrfToken: req.csrfToken() });
});

app.post('/submit', csrfProtection, (req, res) => {
  // csurf validates _csrf field automatically
  res.json({ ok: true });
});
<!-- Include hidden CSRF field in every form -->
<form method="POST" action="/submit">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
  <!-- form fields -->
</form>

Double-Submit Cookie Pattern (Stateless APIs)

For SPAs where the backend is stateless:

import crypto from 'crypto';

function csrfMiddleware(req: Request, res: Response, next: NextFunction) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();

  const cookieToken = req.cookies['csrf-token'];
  const headerToken = req.headers['x-csrf-token'];

  if (!cookieToken || !headerToken || cookieToken !== headerToken) {
    return res.status(403).json({ error: 'CSRF validation failed' });
  }
  next();
}

// On session creation, set the cookie
function setCSRFCookie(res: Response) {
  const token = crypto.randomBytes(32).toString('hex');
  res.cookie('csrf-token', token, {
    secure: true,
    sameSite: 'strict',
    // NOT httpOnly — frontend JS must be able to read it
  });
}
// SPA — send CSRF token on every mutating request
const csrfToken = document.cookie
  .split('; ')
  .find((row) => row.startsWith('csrf-token='))
  ?.split('=')[1];

fetch('/api/update', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': csrfToken ?? '',
  },
  body: JSON.stringify(data),
});

Origin Header Validation

Simplest approach for API-only backends that don't serve HTML:

const ALLOWED_ORIGINS = new Set(['https://app.example.com', 'https://www.example.com']);

function originValidator(req: Request, res: Response, next: NextFunction) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();

  const origin = req.headers.origin || req.headers.referer;
  if (!origin) return res.status(403).json({ error: 'Missing origin' });

  const url = new URL(origin);
  const originBase = `${url.protocol}//${url.host}`;

  if (!ALLOWED_ORIGINS.has(originBase)) {
    return res.status(403).json({ error: 'Invalid origin' });
  }
  next();
}

Details

CSRF is only possible when:

  1. The browser automatically sends credentials (cookies, Basic auth) with cross-origin requests
  2. The server cannot distinguish legitimate from forged requests

APIs using Bearer tokens in Authorization header are immune to CSRF — browsers do not automatically send Authorization headers cross-origin. Only protect cookie-authenticated routes.

Defense selection guide:

NestJS — CsrfGuard:

import { CsrfGuard } from '@tekuconcept/nestjs-csrf';

@UseGuards(CsrfGuard)
@Post('transfer')
transfer(@Body() dto: TransferDto) { ... }

Source

https://owasp.org/www-project-top-ten/

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.