Skip to main content

Overview

The csrf2 middleware provides enhanced CSRF protection using the double submit cookie pattern, where a token is stored in both a cookie and must be submitted in a header or form field. Use it when you need:
  • Stateless CSRF protection
  • Cookie-based token validation
  • Enhanced security for SPAs

Installation

Quick Start

Configuration

Options

Examples

Basic Usage

Secure Configuration

Custom Error Handler

Get Token for Forms

How It Works

  1. Middleware sets CSRF token in cookie
  2. Client reads cookie and includes token in header/form
  3. On state-changing requests, token is validated
  4. If tokens match, request proceeds
  5. If not, returns 403 Forbidden

API Reference

Functions

Client Implementation

JavaScript (SPA)

Technical Details

Token Generation

The middleware generates cryptographically secure tokens using the following process:
  1. Random Bytes: Generates random bytes using crypto/rand
  2. Timestamp: Appends current Unix timestamp for rotation support
  3. Signature: Signs the token with SHA-256 using the provided secret
  4. Encoding: Base64 URL-safe encoding for transport

Token Validation

Token validation uses constant-time comparison to prevent timing attacks:
  1. Decode: Both cookie and submitted tokens are base64-decoded
  2. Length Check: Validates minimum token length (8 bytes)
  3. Constant-Time Compare: Uses XOR-based comparison across all bytes
  4. Result: Returns validation result without early exit
Tokens are stored in HTTP cookies with configurable security options:
  • HttpOnly: Default true to prevent JavaScript access
  • Secure: Configurable for HTTPS enforcement
  • SameSite: Default Lax mode for CSRF protection
  • MaxAge: Default 24 hours (86400 seconds)
  • Path: Default ”/” for site-wide availability

Token Retrieval

The middleware checks for tokens in the following order:
  1. Header: Checks configured header name (default: X-CSRF-Token)
  2. Form: Parses form data for configured field name (default: _csrf)
  3. Query: Checks URL query parameters as fallback

Origin Validation

When enabled, the middleware validates request origin:
  1. Origin Header: Primary validation source
  2. Referer Fallback: Used if Origin header is missing
  3. Allowed Origins: Compares against configured whitelist
  4. Host Match: Falls back to request host if no whitelist specified

Advanced Features

  • Token Masking: XOR-based masking for additional security
  • Fingerprinting: SHA-256 hash of User-Agent and Accept headers
  • Form Input: HTML helper for hidden form fields
  • Meta Tag: HTML meta tag helper for SPAs

Best Practices

  • Always use HTTPS in production
  • Use SameSite Strict for sensitive applications
  • Include token in all state-changing requests
  • Regenerate tokens on authentication changes

Testing

Test Coverage

  • csrf - Basic CSRF protection
  • session - Session management
  • secure - Security settings