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

codeTap to expand ⛶
1// XSS Prevention
2// ❌ BAD — Vulnerable!
3const userInput = '<img src=x onerror=alert("hacked")>';
4element.innerHTML = userInput; // Script executes!
5
6// ✅ GOOD — Use textContent (no HTML parsing)
7element.textContent = userInput; // Safe — displays as text
8
9// ✅ GOOD — Sanitize HTML
10function sanitizeHTML(str) {
11 const div = document.createElement("div");
12 div.textContent = str;
13 return div.innerHTML; // Entities are escaped
14}
15
16// CSRF Prevention — Include token with requests
17async 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 this
24 },
25 body: JSON.stringify(data),
26 credentials: "same-origin"
27 });
28}
29
30// CSP — Set via HTTP header or meta tag
31// Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com;
32// <meta http-equiv="Content-Security-Policy" content="default-src 'self'">
33
34// Input validation
35function validateInput(input) {
36 const clean = input.replace(/[<>'"]/g, ""); // Strip dangerous chars
37 if (clean.length > 1000) throw new Error("Input too long");
38 return clean;
39}
40
41// Secure cookie settings
42// Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/
43
44// Subresource Integrity (SRI) for CDN scripts
45// <script src="https://cdn.example.com/lib.js"
46// integrity="sha384-..." crossorigin="anonymous"></script>

🏋️ Practice Exercise

Mini Exercise:

  1. Identify and fix XSS vulnerabilities in a given HTML/JS snippet
  2. Implement CSRF token validation in a form submission
  3. Write a Content Security Policy header for a web application
  4. Build an input sanitizer that prevents common injection attacks

⚠️ Common Mistakes

  • Using innerHTML with user input — always use textContent or 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(), or innerHTML with untrusted data

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Security (XSS, CSRF, CSP). Login to unlock this feature.