Skip to main content
skill CX Codex

csrf-protection — Claude Code skill: CSRF defense for web forms

A skill that walks your agent through CSRF protection: synchronizer tokens, double-submit cookies and SameSite attributes.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill csrf-protection -a claude-code
Open on GitHub

What csrf-protection does

The skill covers three ways to stop Cross-Site Request Forgery: a hidden form field validated on the server, a cookie and header pair that must match, and the SameSite attribute on cookies. Working Express examples come with it — token generation via crypto.randomBytes, middleware that stores the token in the session, and validation on POST routes.

Token comparison uses crypto.timingSafeEqual. That function throws a RangeError when the buffers differ in length, so the example checks length first. Paste the comparison without that check and your validation crashes instead of returning a clean 403. Worth reading the whole snippet.

Session cookie settings (httpOnly, secure, sameSite), the hidden _csrf field in an HTML form, and a list of common mistakes are all there: tokens in localStorage, tokens reused across sessions, no expiry. For Flask and React the skill points to references/python-react.md, which has a Flask-WTF setup and hooks for token handling.

What it helps with

  • protect a POST form from requests forged on another site
  • generate and validate a CSRF token in Express without an extra library
  • set SameSite and secure on the session cookie
  • compare tokens without a timing leak via timingSafeEqual
  • catch mistakes like keeping the token in localStorage

Example prompts for the agent

  • add CSRF protection to my transfer form with a synchronizer token
  • review my Express POST routes and flag missing token validation
  • set SameSite=Strict on the session cookie

How to install csrf-protection

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill csrf-protection -a claude-code

2Manually: put the files in place

~/.claude/skills/csrf-protection/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/csrf-protection/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about csrf-protection

How do I install csrf-protection in Claude?

Run npx skills add secondsky/claude-skills --skill csrf-protection -a claude-code. The skill then lands in ~/.claude/skills/csrf-protection/SKILL.md.

What does csrf-protection do?

It lays out CSRF defense through synchronizer tokens, double-submit cookies and the SameSite attribute, with Express code samples.

Does it need extra libraries?

The Express examples rely on the built-in crypto module, and for Flask and React the skill links to references/python-react.md with a Flask-WTF setup.

Source text

SKILL.md · MIT
---
name: csrf-protection
description: Implements CSRF protection using synchronizer tokens, double-submit cookies, and SameSite attributes. Use when securing web forms, protecting state-changing endpoints, or implementing defense-in-depth authentication.
license: MIT
---

# CSRF Protection

Defend against Cross-Site Request Forgery attacks using multiple protection layers.

## Protection Methods

| Method | How It Works | Browser Support |
|--------|--------------|-----------------|
| Synchronizer Token | Hidden form field validated server-side | All |
| Double Submit | Cookie + header must match | All |
| SameSite Cookie | Browser blocks cross-origin requests | Modern |

## Token-Based Protection (Express)

```javascript
const crypto = require('crypto');

function generateToken() {
  return crypto.randomBytes(32).toString('hex');
}

// Middleware
app.use((req, res, next) => {
  if (!req.session.csrfToken) {
    req.session.csrfToken = generateToken();
  }
  res.locals.csrfToken = req.session.csrfToken;
  next();
});

// Validation
app.post('*', (req, res, next) => {
  const token = req.body._csrf || req.headers['x-csrf-token'];
  // crypto.timingSafeEqual throws RangeError when buffers differ in length,
  // so check length explicitly first (still constant-time on the equal-length path).
  const csrf = req.session.csrfToken || '';
  if (!token || token.length !== csrf.length) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }
  if (!crypto.timingSafeEqual(Buffer.from(token), Buffer.from(csrf))) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }
  next();
});
```

## SameSite Cookies

```javascript
app.use(session({
  cookie: {
    httpOnly: true,
    secure: true,
    sameSite: 'strict', // or 'lax'
    maxAge: 3600000
  }
}));
```

## HTML Form Integration

```html
<form method="POST" action="/transfer">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>">
  <button type="submit">Submit</button>
</form>
```

## Best Practices

- Apply to all state-changing requests (POST, PUT, DELETE)
- Use SameSite=Strict for sensitive cookies
- Validate Origin/Referer headers
- Never use GET for modifications
- Implement token expiration (1 hour typical)
- Combine multiple defense layers

## Additional Implementations

See [references/python-react.md](references/python-react.md) for:
- Flask-WTF complete CSRF setup
- React hooks for CSRF token management
- Double submit cookie pattern

## Common Mistakes

- Assuming authentication prevents CSRF
- Reusing tokens across sessions
- Storing tokens in localStorage
- Missing token expiration

© secondsky · MIT · secondsky/claude-skills

Similar skills

Everything for Security →

From the same set89

threejs A skill with reference files and working examples for Three.js: scenes, materials, lighting, shaders, GLTF loading. Useful when you build 3D in the browser. CX Codex +1 460installs ml-model-training A skill that walks the agent through the full model training cycle: data prep, splitting, training and evaluation. Useful when you need a classifier or regressor without skipping steps. CX Codex +1 457installs payment-gateway-integration A skill for wiring Stripe, PayPal or Square into your app: payment intents, subscriptions, webhooks and refunds. Useful when you build checkout or billing. CX Codex +1 454installs api-reference-documentation Turns an OpenAPI spec into a developer-facing API reference: endpoints, auth, request and response examples. Useful for SDK docs and developer portals. CX Codex +1 454installs bun-hono-integration A skill that tells the agent how to build Hono APIs on Bun: routes, middleware, Zod validation, RPC client. Useful when your project already runs on Bun. CX Codex +1 452installs interaction-design A skill for designing interface feedback: loading states, errors, empty screens, animation timing and accessibility. Useful when you need to plan how UI behaves, not just how it looks. CX Codex +1 441installs api-error-handling The skill sets a standard error response shape, an ApiError class and a circuit breaker. Useful once your API hits production. CX Codex +1 440installs security-headers-configuration Sets up HTTP security headers against XSS, clickjacking and MIME sniffing. Useful when hardening an app or preparing for an audit. CX Codex +1 438installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor