CSRF Protection Implementation
security
TypeScript
code_review
strict_senior
Protect against Cross-Site Request Forgery with tokens and SameSite cookies.
By lucas_a
12/8/2025
Prompt
Implement comprehensive CSRF (Cross-Site Request Forgery) protection for the following application with token generation, validation, and secure cookie configuration:
Application Details
Application Overview
- Application Type: [Web app / API / Full-stack / SPA with backend]
- Framework: [Express / Next.js / Django / Flask / Spring Boot / ASP.NET]
- Frontend: [React / Vue / Angular / Server-rendered / Vanilla JS]
- Session Management: [Express-session / Redis / Database / JWT / Custom]
- Authentication: [Session-based / JWT / OAuth / Custom]
Current State
- CSRF Protection: [None currently / Partial / Need to enhance]
- Cookie Configuration: [Current settings or None]
- Security Headers: [Implemented / Not implemented]
- HTTPS: [Enforced / Not enforced / Development only]
Protected Endpoints
State-Changing Endpoints
List all endpoints that modify data (require CSRF protection):
Endpoint 1: [Name, e.g., Create User]
- Method: [POST / PUT / PATCH / DELETE]
- Path: [/api/users / /users/create]
- Request Type: [Form submission / JSON API / Multipart form]
- Authentication Required: [Yes / No]
- Sensitivity: [High / Medium / Low]
Endpoint 2: [Name, e.g., Update Profile]
- Method: [Method]
- Path: [Path]
- Request Type: [Type]
- Authentication Required: [Yes / No]
- Sensitivity: [Level]
Endpoint 3: [Name, e.g., Delete Account]
- Method: [Method]
- Path: [Path]
- Request Type: [Type]
- Authentication Required: [Yes / No]
- Sensitivity: [Level]
[List 5-20 state-changing endpoints]
Safe Methods (No CSRF Protection Needed)
- GET Requests: [All GET requests are safe]
- HEAD Requests: [Safe]
- OPTIONS Requests: [Safe]
CSRF Protection Strategy
Token Generation
- Token Type: [Synchronizer token / Double-submit cookie / Both]
- Token Length: [32 bytes / 64 bytes / Custom]
- Token Storage: [Session / Database / Memory / Redis]
- Token Rotation: [Per request / Per session / After auth / Never]
- Token Expiration: [Session lifetime / 1 hour / 24 hours / Custom]
Token Validation
- Validation Method: [Header-based / Form field / Both]
- Header Name: [X-CSRF-Token / X-XSRF-Token / Custom]
- Form Field Name: [_csrf / csrf_token / Custom]
- Validation Timing: [Before route handler / In middleware / Custom]
Protection Scope
- Apply To: [All POST/PUT/PATCH/DELETE / Specific routes / Custom]
- Exemptions: [Public API endpoints / Webhooks / Custom]
- API vs Web: [Different strategies / Same strategy]
Cookie Configuration
Session Cookie
- Cookie Name: [connect.sid / sessionId / Custom]
- HttpOnly: [true / false]
- Secure: [true (HTTPS only) / false (dev) / Environment-based]
- SameSite: [Strict / Lax / None]
- Domain: [Specific domain / Subdomain / Default]
- Path: [/ / /app / Custom]
- Max Age: [Session / 1 hour / 24 hours / 7 days]
CSRF Token Cookie (if using double-submit)
- Cookie Name: [XSRF-TOKEN / csrf-token / Custom]
- HttpOnly: [false (must be readable by JS)]
- Secure: [true / false / Environment-based]
- SameSite: [Strict / Lax]
- Domain: [Same as session cookie]
- Path: [/]
- Max Age: [Same as session / Custom]
Implementation Requirements
Backend Implementation
Token Generation
- Generation Method: [crypto.randomBytes / uuid / Custom]
- Storage Location: [req.session.csrfToken / Redis / Database]
- Token Refresh: [On every request / On auth / Manual]
Middleware
- Global Middleware: [Apply to all routes / Selective]
- Validation Logic: [Compare header/body token with session]
- Error Response: [403 Forbidden / 401 Unauthorized / Custom]
- Logging: [Log CSRF failures / No logging]
Route Protection
- Protected Routes: [List specific routes or patterns]
- Exempted Routes: [Public APIs, webhooks, health checks]
- Custom Validation: [Additional checks for sensitive operations]
Frontend Implementation
Token Retrieval
- Method: [Meta tag / Cookie / API endpoint / Hidden in DOM]
- Storage: [Memory / LocalStorage / SessionStorage / None]
- Refresh Strategy: [On page load / Before each request / Manual]
Token Inclusion
For Forms
- Hidden Input: [Include _csrf field in all forms]
- Auto-injection: [Automatically add to forms / Manual]
- Template Integration: [How to pass token to templates]
For AJAX/Fetch
- Header Name: [X-CSRF-Token / X-XSRF-Token]
- Automatic Inclusion: [Axios interceptor / Fetch wrapper / Manual]
- Error Handling: [Retry with new token / Show error / Custom]
For SPAs
- Initial Token: [From meta tag / API call / Server-rendered]
- Token Refresh: [On 403 / Periodic / Manual]
- State Management: [Redux / Context / Local state]
Security Enhancements
SameSite Cookie Policy
- Strict Mode: [For sensitive operations]
- Lax Mode: [For general navigation]
- None Mode: [Only if cross-site requests needed with Secure flag]
- Fallback: [For older browsers]
Additional Protections
- Origin Validation: [Check Origin/Referer headers]
- Custom Headers: [Require custom header for API calls]
- Rate Limiting: [Limit failed CSRF attempts]
- CORS Configuration: [Strict CORS policy]
- Content Security Policy: [CSP headers]
High-Security Operations
For critical operations (delete account, financial transactions):
- Double Verification: [CSRF + Password / CSRF + 2FA]
- Per-Request Tokens: [New token for each request]
- Time-Limited Tokens: [Short expiration]
- User Confirmation: [Explicit confirmation required]
Error Handling
CSRF Validation Failures
- Error Response: [JSON error / Redirect / Custom page]
- Status Code: [403 / 401 / Custom]
- Error Message: [Generic / Detailed / Custom]
- Logging: [Log IP, user, endpoint, timestamp]
- Alerting: [Alert on multiple failures / No alerts]
Token Expiration
- Handling: [Redirect to login / Refresh token / Show error]
- User Experience: [Preserve form data / Clear form / Custom]
- Grace Period: [Allow expired token for X seconds / No grace]
Missing Token
- Response: [403 error / Redirect / Custom]
- User Guidance: [Helpful error message / Generic message]
Testing Requirements
Test Cases
- Valid Token: [Request with correct token succeeds]
- Invalid Token: [Request with wrong token fails]
- Missing Token: [Request without token fails]
- Expired Token: [Expired token is rejected]
- Token Reuse: [Used token cannot be reused (if per-request)]
- Cross-Origin: [Cross-origin requests are blocked]
- Safe Methods: [GET/HEAD/OPTIONS work without token]
Security Testing
- CSRF Attack Simulation: [Attempt CSRF attack from external site]
- Token Leakage: [Ensure tokens not in URLs or logs]
- Cookie Security: [Verify cookie flags are correct]
- SameSite Effectiveness: [Test SameSite protection]
Code Generation Requirements
Generate a complete CSRF protection implementation including:
-
Backend Middleware:
- Token generation function with crypto
- Session/cookie storage for tokens
- CSRF validation middleware
- Error handling for validation failures
- Route exemption logic
- Token rotation logic
-
Route Protection:
- Apply middleware to protected routes
- Exemption list for public endpoints
- Custom validation for sensitive operations
- Proper error responses
-
Cookie Configuration:
- Session cookie setup with proper flags
- CSRF token cookie (if double-submit pattern)
- SameSite configuration
- Secure and HttpOnly flags
- Environment-based configuration
-
Frontend Integration:
- Meta tag for token in HTML templates
- JavaScript token retrieval function
- Fetch/Axios interceptor for automatic header inclusion
- Form helper to inject hidden CSRF fields
- Error handling for CSRF failures
-
Form Templates:
- HTML form examples with CSRF token
- Template syntax for server-side rendering
- Auto-injection script for dynamic forms
-
API Client:
- Configured HTTP client with CSRF headers
- Token refresh logic
- Error handling and retry logic
-
Security Headers:
- Helmet.js configuration (if Node.js)
- CSP headers
- CORS configuration
- Origin validation
-
Testing Suite:
- Unit tests for token generation
- Integration tests for protected endpoints
- Security tests for CSRF attacks
- Test utilities for mocking tokens
-
Documentation:
- Implementation guide
- Security best practices
- Troubleshooting guide
- Migration guide (if adding to existing app)
-
Configuration:
- Environment variables for secrets
- Development vs production settings
- Cookie domain configuration
- Token expiration settings
Output production-ready CSRF protection following best practices with:
- Cryptographically secure token generation
- Proper session/cookie configuration
- SameSite cookie policy
- Comprehensive validation middleware
- Frontend integration for forms and AJAX
- Clear error messages and logging
- Protection for all state-changing operations
- Exemptions for safe methods and public APIs
- Testing coverage for security scenarios
- HTTPS enforcement in production
- Token rotation for sensitive operations
- Origin/Referer validation
- Rate limiting for failed attempts
- Clear documentation and examples
Tags
csrf
security
web-security
tokens
Tested Models
gpt-4
claude-3-opus