Csrf Protection

by secondsky88378361314fMIT227 starsListed Oct 8, 2026Updated Oct 8, 2026Repository updated 10 days ago

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.

AI-generated overview

Guides implementing CSRF protection with synchronizer tokens, double-submit cookies, and SameSite cookie attributes.

What it does
This skill provides instructions and code examples for defending web applications against Cross-Site Request Forgery. It covers synchronizer token generation and validation in Express, SameSite cookie configuration, HTML form integration, and best practices such as token expiration and Origin/Referer validation. It also points to a reference file with Flask-WTF setup, React token management hooks, and the double-submit cookie pattern.
When to use it
Use it when securing web forms, protecting state-changing endpoints, or adding defense-in-depth to authentication flows. It is intended for developers implementing CSRF defenses in web applications.
Requirements
No scripts are shipped; it is instructions only. The examples assume a JavaScript/Express environment with session middleware and Node's crypto module, and the reference file covers Python/Flask and React.

CSRF Protection

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

Protection Methods

MethodHow It WorksBrowser Support
Synchronizer TokenHidden form field validated server-sideAll
Double SubmitCookie + header must matchAll
SameSite CookieBrowser blocks cross-origin requestsModern

Token-Based Protection (Express)

javascript
const crypto = require('crypto');
function generateToken() {  return crypto.randomBytes(32).toString('hex');}
// Middlewareapp.use((req, res, next) => {  if (!req.session.csrfToken) {    req.session.csrfToken = generateToken();  }  res.locals.csrfToken = req.session.csrfToken;  next();});
// Validationapp.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 [blocked] 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

Source and attribution

Source:secondsky/claude-skillsinplugins/csrf-protection/skills/csrf-protectionat commit8837836

License: MIT

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Report or request removal