Skip to main content

Overview

The csrf middleware protects against Cross-Site Request Forgery attacks by generating and validating tokens. It ensures that form submissions originate from your application, not from malicious sites. Use it when you have:
  • HTML forms that modify data
  • Server-rendered applications
  • Any POST/PUT/DELETE endpoints accessed via browser

Installation

Quick Start

Configuration

Options

TokenLookup Format

The TokenLookup option uses "source:name" format:

Examples

Basic Form Protection

Using Template Field Helper

JavaScript AJAX Requests

Skip API Routes

Custom Error Handler

Multiple Token Sources

Development vs Production

API Reference

Functions

Token Functions

Error Types

How It Works

  1. Token Generation: On GET requests, a token is generated and stored in a cookie
  2. Token Validation: On POST/PUT/DELETE requests, the token must be included
  3. Double Submit: The cookie token must match the request token
  4. HMAC Signature: Tokens are signed to prevent tampering

Technical Details

Token Generation

The middleware generates cryptographically secure tokens using the following process:
  1. Random Bytes: Generates random bytes of specified length (default 32) using crypto/rand
  2. HMAC Signature: Creates an HMAC-SHA256 signature of the random bytes using the secret key
  3. Encoding: Encodes both the token and signature using base64 URL encoding
  4. Format: Combines them as token.signature for tamper detection

Token Validation

Validation follows a multi-step process to ensure security:
  1. Constant-Time Comparison: Uses subtle.ConstantTimeCompare to prevent timing attacks
  2. Cookie-Request Match: Verifies the cookie token exactly matches the request token
  3. Signature Verification: Decodes and validates the HMAC signature
  4. HMAC Equality: Uses hmac.Equal for secure signature comparison

Safe vs Unsafe Methods

The middleware distinguishes between HTTP methods:
  • Safe Methods (GET, HEAD, OPTIONS, TRACE): Generate or reuse tokens, no validation required
  • Unsafe Methods (POST, PUT, DELETE, PATCH): Require valid token in both cookie and request

Context Storage

Tokens are stored in the request context using a private contextKey type to prevent collisions with other middleware or application code. This allows retrieval via the Token() function throughout the request lifecycle.

Path Skipping

The SkipPaths option uses a map for O(1) lookup performance, allowing specific routes (like webhooks or public APIs) to bypass CSRF validation entirely.

Security Considerations

  1. Secret Key - Use a strong, random 32-byte secret
  2. Cookie Settings - Use Secure, HttpOnly, and SameSite in production
  3. Token Rotation - Tokens are per-session, not per-request
  4. HTTPS Required - Always use HTTPS in production

Best Practices

  • Always include CSRF protection for forms
  • Use secure cookies in production
  • Skip CSRF for API endpoints using Bearer auth
  • Regenerate token after login/logout
  • Set appropriate cookie expiration

Testing

The CSRF middleware includes comprehensive test coverage for all functionality: