CSRF Protection

Comprehensive Cross-Site Request Forgery protection for webMCP applications. Secure your forms and APIs against CSRF attacks.

CSRF Protection Features

Advanced CSRF protection mechanisms for modern web applications

Automatic Token Generation

Generate cryptographically secure CSRF tokens automatically

  • Cryptographically secure random tokens
  • Configurable token length and format
  • Automatic token rotation
  • Per-session token management

Token Validation

Validate CSRF tokens on all state-changing requests

  • Automatic header validation
  • Form input token checking
  • Double-submit cookie pattern
  • Custom validation rules

Framework Integration

Seamless integration with popular web frameworks

  • Express.js middleware
  • Django middleware support
  • Flask integration
  • Custom framework adapters

Implementation Examples

Practical examples for implementing CSRF protection in your applications

Basic CSRF Protection

Enable CSRF protection with default settings

JavaScript
import { WebMCPProcessor } from '@webmcp/core';

const processor = new WebMCPProcessor({
  security: {
    enable_csrf: true,
    csrf_token_expiry: 3600, // 1 hour
    csrf_cookie_name: '_webmcp_csrf',
    csrf_header_name: 'X-CSRF-Token'
  }
});

// Generate CSRF token for form
const csrfToken = processor.generateCSRFToken();

// Include in HTML form
const formHtml = `
<form method="POST" action="/login">
  <input type="hidden" name="_csrf" value="${csrfToken}" />
  <input type="email" name="email" required />
  <input type="password" name="password" required />
  <button type="submit">Login</button>
</form>
`;

Double-Submit Cookie Pattern

Implement double-submit cookie pattern for SPA applications

JavaScript
// Server-side: Set CSRF token in cookie and return in response
app.use('/api', (req, res, next) => {
  const csrfToken = processor.generateCSRFToken();
  
  // Set secure cookie
  res.cookie('csrf-token', csrfToken, {
    httpOnly: false, // Allow JS access for SPA
    secure: true,
    sameSite: 'strict',
    maxAge: 3600000 // 1 hour
  });
  
  // Also provide in response header
  res.set('X-CSRF-Token', csrfToken);
  next();
});

// Client-side: Include token in AJAX requests
const csrfToken = document.cookie
  .split(';')
  .find(row => row.startsWith('csrf-token='))
  ?.split('=')[1];

fetch('/api/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': csrfToken
  },
  body: JSON.stringify({ email, password })
});

Custom Validation Rules

Implement custom CSRF validation logic

JavaScript
const processor = new WebMCPProcessor({
  security: {
    enable_csrf: true,
    csrf_validation: {
      // Custom validation function
      validate: (token, request) => {
        // Check token format
        if (!token || typeof token !== 'string') {
          return { valid: false, error: 'Invalid token format' };
        }
        
        // Check token length
        if (token.length !== 64) {
          return { valid: false, error: 'Invalid token length' };
        }
        
        // Verify token signature
        const isValid = processor.verifyCSRFToken(token, request.sessionId);
        
        return { 
          valid: isValid, 
          error: isValid ? null : 'Token verification failed' 
        };
      },
      
      // Custom error handler
      onValidationError: (error, request, response) => {
        console.error('CSRF validation failed:', error);
        response.status(403).json({
          error: 'CSRF token validation failed',
          message: 'Please refresh the page and try again'
        });
      }
    }
  }
});

Python Implementation

CSRF protection in Python applications

Python
from webmcp_core import WebMCPProcessor, CSRFConfig
from flask import Flask, request, session, abort
import secrets

app = Flask(__name__)
processor = WebMCPProcessor(
    security=CSRFConfig(
        enable_csrf=True,
        token_expiry=3600,
        secret_key=os.getenv('CSRF_SECRET_KEY')
    )
)

@app.before_request
def csrf_protect():
    if request.method in ['POST', 'PUT', 'DELETE', 'PATCH']:
        token = request.form.get('_csrf') or request.headers.get('X-CSRF-Token')
        
        if not token:
            abort(403, 'CSRF token missing')
            
        if not processor.verify_csrf_token(token, session.get('session_id')):
            abort(403, 'CSRF token invalid')

@app.route('/form')
def show_form():
    csrf_token = processor.generate_csrf_token(session['session_id'])
    return render_template('form.html', csrf_token=csrf_token)

@app.route('/login', methods=['POST'])
def login():
    # CSRF validation happens automatically in before_request
    email = request.form['email']
    password = request.form['password']
    # Process login...
    return redirect('/dashboard')

Security Considerations

Best practices and security considerations for CSRF protection

Token Security

Use Cryptographically Secure Tokens

Generate tokens using cryptographically secure random number generators

Use crypto.randomBytes() or secrets.token_urlsafe() for token generation

Proper Token Length

Use sufficiently long tokens to prevent brute force attacks

Minimum 32 bytes (256 bits) of entropy for CSRF tokens

Token Rotation

Rotate tokens regularly to limit exposure window

Generate new tokens on each session or after specified time intervals

Cookie Security

Secure Cookie Attributes

Use proper cookie attributes for CSRF token cookies

Set Secure, SameSite=Strict, and appropriate HttpOnly flags

Domain and Path Restrictions

Limit cookie scope to prevent cross-subdomain issues

Set explicit domain and path attributes on CSRF cookies

Cookie Expiration

Set appropriate expiration times for CSRF cookies

Align cookie expiration with token expiration times

Implementation Best Practices

Validate All State-Changing Requests

Apply CSRF protection to all POST, PUT, DELETE, PATCH requests

Use middleware or decorators to enforce CSRF validation

Graceful Error Handling

Provide clear error messages and recovery options

Return 403 status with instructions to refresh the page

Logging and Monitoring

Log CSRF validation failures for security monitoring

Include request details and user information in CSRF logs

Troubleshooting Guide

Common CSRF issues and their solutions

CSRF Token Missing

Symptoms

  • 403 Forbidden errors
  • Forms not submitting
  • AJAX requests failing

Possible Causes

  • Token not included in form or headers
  • JavaScript not reading cookie correctly
  • Server not generating tokens

Solutions

  • Verify token is included in form hidden input
  • Check AJAX requests include X-CSRF-Token header
  • Ensure server generates and sets CSRF tokens

CSRF Token Invalid

Symptoms

  • Token validation failures
  • Expired token errors
  • Session mismatch

Possible Causes

  • Token expired due to time limit
  • Session ID mismatch
  • Token tampering or corruption

Solutions

  • Increase token expiration time
  • Verify session management is working
  • Check for token corruption in transmission

SPA Integration Issues

Symptoms

  • CSRF failures in single-page apps
  • Token not available to JavaScript

Possible Causes

  • HttpOnly cookies preventing JS access
  • CORS issues with token headers
  • Token not refreshed on navigation

Solutions

  • Use double-submit cookie pattern
  • Configure CORS to allow CSRF headers
  • Implement token refresh mechanism

Secure Your Applications

Implement CSRF protection to secure your webMCP applications against cross-site request forgery attacks