Security (XSS, CSRF, CSP)
📖 Concept
Web security is critical for protecting users and data. Key threats:
XSS (Cross-Site Scripting) — Attacker injects malicious scripts into your page. Types: Stored, Reflected, DOM-based. CSRF (Cross-Site Request Forgery) — Attacker tricks user's browser into making unwanted requests to a site where they're authenticated. CSP (Content Security Policy) — HTTP header that controls which resources the browser is allowed to load.
🏠 Real-world analogy: XSS is like someone slipping a fake page into a library book — the next reader follows the fake instructions. CSRF is like someone forging your signature on a bank check. CSP is like a security guard with a guest list — only approved resources get in.
💻 Code Example
1// XSS Prevention2// ❌ BAD — Vulnerable!3const userInput = '<img src=x onerror=alert("hacked")>';4element.innerHTML = userInput; // Script executes!56// ✅ GOOD — Use textContent (no HTML parsing)7element.textContent = userInput; // Safe — displays as text89// ✅ GOOD — Sanitize HTML10function sanitizeHTML(str) {11 const div = document.createElement("div");12 div.textContent = str;13 return div.innerHTML; // Entities are escaped14}1516// CSRF Prevention — Include token with requests17async function submitForm(data) {18 const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;19 const response = await fetch("/api/submit", {20 method: "POST",21 headers: {22 "Content-Type": "application/json",23 "X-CSRF-Token": csrfToken // Server validates this24 },25 body: JSON.stringify(data),26 credentials: "same-origin"27 });28}2930// CSP — Set via HTTP header or meta tag31// Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com;32// <meta http-equiv="Content-Security-Policy" content="default-src 'self'">3334// Input validation35function validateInput(input) {36 const clean = input.replace(/[<>'"]/g, ""); // Strip dangerous chars37 if (clean.length > 1000) throw new Error("Input too long");38 return clean;39}4041// Secure cookie settings42// Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/4344// Subresource Integrity (SRI) for CDN scripts45// <script src="https://cdn.example.com/lib.js"46// integrity="sha384-..." crossorigin="anonymous"></script>
🏋️ Practice Exercise
Mini Exercise:
- Identify and fix XSS vulnerabilities in a given HTML/JS snippet
- Implement CSRF token validation in a form submission
- Write a Content Security Policy header for a web application
- Build an input sanitizer that prevents common injection attacks
⚠️ Common Mistakes
Using
innerHTMLwith user input — always usetextContentor a sanitizer library (DOMPurify)Storing auth tokens in localStorage — XSS can steal them. Use HttpOnly cookies instead
Not using SameSite on cookies — leaves you vulnerable to CSRF
Trusting client-side validation only — always validate on the server too
Using
eval(),new Function(), orinnerHTMLwith untrusted data
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Security (XSS, CSRF, CSP). Login to unlock this feature.