✅ Secure CSRF Examples - Protection Mechanisms

Learn how to properly protect against Cross-Site Request Forgery attacks

✅ Security Features Implemented:

🔐 CSRF Token Protection

Generate and validate unique tokens for each request:

Current CSRF Token: Loading...
// ✅ SECURE: CSRF token generation and validation function generateCSRFToken() { return crypto.getRandomValues(new Uint8Array(32)) .reduce((acc, val) => acc + val.toString(16).padStart(2, '0'), ''); } function validateCSRFToken(token) { const storedToken = sessionStorage.getItem('csrfToken'); return token === storedToken; } // ✅ SECURE: Include token in requests const token = generateCSRFToken(); sessionStorage.setItem('csrfToken', token); formData.append('csrfToken', token);

🍪 SameSite Cookie Protection

Configure cookies to prevent cross-site requests:

Secure Cookie Configuration:
  • SameSite=Strict - Blocks all cross-site requests
  • Secure - Only sent over HTTPS
  • HttpOnly - Not accessible via JavaScript
  • Path=/ - Limited to specific path
// ✅ SECURE: SameSite cookie configuration function setSecureCookie(name, value) { const expires = new Date(); expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000)); // 24 hours document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; secure; samesite=strict; httponly`; } // Server-side equivalent (Node.js/Express) res.cookie('sessionId', sessionId, { httpOnly: true, secure: true, sameSite: 'strict', maxAge: 24 * 60 * 60 * 1000 });

🌐 Origin Header Validation

Validate request origin to prevent cross-site attacks:

// ✅ SECURE: Origin header validation function validateOrigin(origin) { const allowedOrigins = [ 'https://trusted-site.com', 'https://secure-bank.com', 'https://api.secure-bank.com' ]; return allowedOrigins.includes(origin); } // Server-side validation (Node.js/Express) app.use((req, res, next) => { const origin = req.headers.origin; const allowedOrigins = ['https://trusted-site.com']; if (allowedOrigins.includes(origin)) { res.setHeader('Access-Control-Allow-Origin', origin); next(); } else { res.status(403).json({ error: 'Invalid origin' }); } });

🔄 Double Submit Cookie Pattern

Use both cookie and form field for CSRF protection:

// ✅ SECURE: Double submit cookie pattern function performDoubleSubmit() { const cookieToken = getCookie('csrfToken'); const formToken = generateCSRFToken(); // Both tokens must match if (cookieToken === formToken) { // Proceed with action return true; } else { // Reject request return false; } } // Server-side validation if (req.cookies.csrfToken === req.body.csrfToken) { // Valid request } else { // Invalid request - potential CSRF attack }

🔒 Re-authentication for Sensitive Operations

Require additional authentication for critical actions:

// ✅ SECURE: Re-authentication for sensitive operations function changePasswordSecure() { const currentPassword = document.getElementById('currentPassword').value; const newPassword = document.getElementById('newPassword').value; // Validate current password first if (validateCurrentPassword(currentPassword)) { // Proceed with password change updatePassword(newPassword); } else { // Reject - invalid current password throw new Error('Invalid current password'); } } // Server-side implementation app.post('/change-password', authenticateUser, (req, res) => { const { currentPassword, newPassword } = req.body; if (validateCurrentPassword(req.user.id, currentPassword)) { updatePassword(req.user.id, newPassword); res.json({ success: true }); } else { res.status(401).json({ error: 'Invalid current password' }); } });

📋 CSRF Protection Best Practices

✅ Do's:

  • Use CSRF tokens for all state-changing requests
  • Implement SameSite=Strict cookies
  • Validate Origin headers
  • Use HTTPS for all requests
  • Re-authenticate for sensitive operations
  • Use double submit cookie pattern

❌ Don'ts:

  • Don't rely on GET requests for state changes
  • Don't use predictable tokens
  • Don't ignore Origin headers
  • Don't use SameSite=None without Secure
  • Don't trust Referer headers alone
  • Don't skip re-authentication for critical actions

🔍 Secure vs Vulnerable Comparison

See the difference between secure and vulnerable CSRF implementations:

❌ Vulnerable Implementation:

  • No CSRF tokens
  • GET requests for state changes
  • No Origin validation
  • SameSite=None cookies
  • No re-authentication

✅ Secure Implementation:

  • CSRF tokens for all requests
  • POST requests only
  • Origin header validation
  • SameSite=Strict cookies
  • Re-authentication for sensitive ops

🛡️ Implementation Checklist

Ensure these CSRF protection measures are in place: