csrf-protection

Implement Cross-Site Request Forgery (CSRF) protection using tokens, SameSite cookies, and origin validation. Use when building forms and state-changing operations.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "csrf-protection" with this command: npx skills add aj-geddes/useful-ai-prompts/aj-geddes-useful-ai-prompts-csrf-protection

CSRF Protection

Table of Contents

Overview

Implement comprehensive Cross-Site Request Forgery protection using synchronizer tokens, double-submit cookies, SameSite cookie attributes, and custom headers.

When to Use

  • Form submissions
  • State-changing operations
  • Authentication systems
  • Payment processing
  • Account management
  • Any POST/PUT/DELETE requests

Quick Start

Minimal working example:

// csrf-protection.js
const crypto = require("crypto");
const csrf = require("csurf");

class CSRFProtection {
  constructor() {
    this.tokens = new Map();
    this.tokenExpiry = 3600000; // 1 hour
  }

  /**
   * Generate CSRF token
   */
  generateToken() {
    return crypto.randomBytes(32).toString("hex");
  }

  /**
   * Create token for session
   */
  createToken(sessionId) {
    const token = this.generateToken();
    const expiry = Date.now() + this.tokenExpiry;

    this.tokens.set(sessionId, {
// ... (see reference guides for full implementation)

Reference Guides

Detailed implementations in the references/ directory:

GuideContents
Node.js/Express CSRF ProtectionNode.js/Express CSRF Protection
Double Submit Cookie PatternDouble Submit Cookie Pattern
Python Flask CSRF ProtectionPython Flask CSRF Protection
Frontend CSRF ImplementationFrontend CSRF Implementation
Origin and Referer ValidationOrigin and Referer Validation

Best Practices

✅ DO

  • Use CSRF tokens for all state-changing operations
  • Set SameSite=Strict on cookies
  • Validate Origin/Referer headers
  • Use secure, random tokens
  • Implement token expiration
  • Use HTTPS only
  • Include tokens in AJAX requests
  • Test CSRF protection

❌ DON'T

  • Skip CSRF for authenticated requests
  • Use GET for state changes
  • Trust Origin header alone
  • Reuse tokens
  • Store tokens in localStorage
  • Allow credentials in CORS without validation

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

nodejs-express-server

No summary provided by upstream source.

Repository SourceNeeds Review
General

markdown-documentation

No summary provided by upstream source.

Repository SourceNeeds Review
General

rest-api-design

No summary provided by upstream source.

Repository SourceNeeds Review
General

architecture-diagrams

No summary provided by upstream source.

Repository SourceNeeds Review