Skill

Implement Robust CSRF Token Handling

A CSRF protection skill covering token generation, storage, and validation with working Express, Django, and PHP implementations.


91
Spark score
out of 100
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Protect your web applications from Cross-Site Request Forgery (CSRF) attacks by implementing expert-level token generation, validation, and secure storage strategies. This asset ensures robust defense mechanisms across various frameworks.

Outcomes

What it gets done

01

Generate cryptographically strong and unique CSRF tokens.

02

Implement secure token validation with expiration and session binding.

03

Integrate CSRF protection into Express.js, Django, and PHP applications.

04

Apply advanced patterns like Double Submit Cookie and Synchronizer Token.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-csrf-token-handler | bash

Overview

CSRF Token Handler Agent

A CSRF protection skill with working token generation, storage, and validation code for Node.js, Python Flask, Express, Django, and PHP. It covers the Double Submit Cookie and Synchronizer Token patterns, complementary security headers, and an automated CSRF test suite. Use it when implementing or auditing CSRF protection on state-changing web endpoints across any of the covered frameworks - not as a general web security guide beyond CSRF and its commonly paired security headers.

What it does

This skill is expert in Cross-Site Request Forgery protection mechanisms, specializing in token generation, validation, storage strategies, and implementation across web frameworks and architectures. Its token requirements call for cryptographically strong unpredictability, uniqueness per session or request, time-based expiration, binding to specific user sessions, and secure transmission channels. It covers understanding attack vectors - vulnerability of state-changing operations, same-origin-policy limitations, cookie-based authentication risks, and cross-site request scenarios - and provides working implementations across stacks: a Node.js CSRFTokenManager generating cryptographically random tokens and timestamp-embedded tokens with expiration validation, a Python Flask CSRFHandler supporting both session-based and in-memory storage with constant-time comparison, Express.js middleware using the csurf package plus a custom header/body token-matching middleware, Django CSRF token views and a custom API-protection decorator checking the X-CSRFToken header or request body, a client-side Double Submit Cookie pattern that auto-attaches a CSRF header to every non-GET fetch call, and a PHP Synchronizer Token pattern using session storage with hash_equals for timing-safe comparison.

When to use - and when NOT to

Use this skill when implementing or auditing CSRF protection for a web application's state-changing endpoints - it covers the full lifecycle from token generation through framework-specific middleware to automated testing (a CSRFTester suite checking token generation, valid-token acceptance, and invalid-token rejection). It names concrete mistakes to avoid: never store tokens in localStorage (XSS-exposed), never use predictable token patterns, never expose tokens in URLs or logs, and always use constant-time comparison for validation. It is not a general web security guide - it's scoped specifically to CSRF, though it does bundle complementary security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy, CSP, and forced SameSite cookie enforcement) since those defenses are commonly deployed alongside CSRF tokens.

Inputs and outputs

// Node.js - Криптографически стойкая генерация токенов
const crypto = require('crypto');

class CSRFTokenManager {
  generateToken(length = 32) {
    return crypto.randomBytes(length).toString('hex');
  }
  
  generateTokenWithTimestamp() {
    const timestamp = Date.now();
    const randomPart = crypto.randomBytes(24).toString('hex');
    const payload = `${timestamp}:${randomPart}`;
    return Buffer.from(payload).toString('base64');
  }
  
  validateTimestampedToken(token, maxAge = 3600000) {
    try {
      const decoded = Buffer.from(token, 'base64').toString();
      const [timestamp, randomPart] = decoded.split(':');
      const tokenAge = Date.now() - parseInt(timestamp);
      return tokenAge <= maxAge && randomPart.length === 48;
    } catch (error) {
      return false;
    }
  }
}

Given a framework and storage preference, the skill produces a token manager or handler class like the one above, framework-specific middleware (Express csurf config with httpOnly/secure/sameSite cookie options, Django CSRF views and decorators, PHP SynchronizerToken with a hidden-input helper), a security-header middleware bundle, and a JavaScript test suite validating token generation, acceptance, and rejection behavior end to end.

Who it's for

Backend and full-stack engineers implementing or auditing CSRF protection who need working, framework-specific code rather than abstract token theory - Node.js/Express, Python/Flask, Django, and PHP are all covered with complete classes. It suits teams that want performance guidance for high-traffic apps (stateless tokens where possible, token caching, rotation policies for long-lived sessions, batch validation) alongside the security implementation itself.

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.