DOM & Browsermedium

XSS vs CSRF — how do you prevent them?

Explain Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). How does each attack work, and what are the mitigations?

Asked at Google, CrowdStrike, Tenable

#security#XSS#CSRF#CSP

Answer

// Usage // Apply these rules for all user-generated content and state-changing APIs. // XSS — attacker injects malicious scripts into your page // ──────────────────────────────────────────────────────── // Attack: // Mitigations: // 1. Escape/sanitise ALL user input before rendering to HTML // 2. Content Security Policy (CSP) header to whitelist sources // 3. HttpOnly cookies (JS can't read them) // 4. Use textContent instead of innerHTML // 5. DOMPurify library for rich-text HTML

// ❌ Vulnerable el.innerHTML = userInput // dangerous // ✅ Safe el.textContent = userInput // auto-escaped el.innerHTML = DOMPurify.sanitize(userInput) // if HTML needed

// ───────────────────────────────────────────────────────── // CSRF — attacker tricks the browser into making auth'd requests // Attack: evil.com has a hidden form that POSTs to bank.com/transfer // Your browser sends the session cookie automatically. // Mitigations: // 1. CSRF tokens (server issues random token, validates on POST) // 2. SameSite=Strict/Lax cookie attribute // 3. Check Origin/Referer header on the server // 4. Require re-authentication for sensitive actions

// Key difference: // XSS = attacker runs code IN your site (trust issue with input) // CSRF = attacker makes your browser make requests TO your site

Source: frontendinterviewhandbook.com — Google

Practise more DOM & Browser questions →