Web Security and WAF · OWASP Top 10 and Common Attacks
Cross-Site Scripting and Content Security Policy
Prevent script injection with output encoding, sanitization and CSP.
XSS lets attackers run JavaScript in your users' browsers (stealing data, acting as the user). Types: stored, reflected and DOM-based. Prevent it with context-aware output encoding (frameworks like React, Angular, Twig and Blade escape by default), sanitizing user HTML with allow-list sanitizers (DOMPurify, nh3), avoiding dangerous sinks (innerHTML, dangerouslySetInnerHTML, eval), and adding a strict CSP with nonces as defense in depth.
Content-Security-Policy:
default-src 'self';
script-src 'nonce-r4nd0m' 'strict-dynamic';
object-src 'none';
base-uri 'self';
frame-ancestors 'none';
report-to csp-endpoint
// DOM XSS sink fix
el.innerHTML = userBio; // BUG:
el.textContent = userBio; // FIX: plain text
el.innerHTML = DOMPurify.sanitize(userHtml); // FIX: when HTML is required
Common pitfalls
- Bypassing framework escaping for convenience.
javascript:URLs in user-supplied links.- CSP with
'unsafe-inline'scripts (little protection).
Key points
- Escape by context; avoid dangerous sinks
- Sanitize HTML with allow-lists
- Strict CSP as defense in depth
Further reading: OWASP XSS Prevention Cheat Sheet
Practice questions
Why is CSP considered defense in depth rather than the primary XSS fix?
Answer
It limits what injected scripts can do or load, but the real fix is not emitting attacker-controlled script in the first place; CSP catches mistakes.
What is DOM-based XSS?
Answer
XSS where client-side JavaScript reads attacker-controlled data (URL fragment, postMessage) and writes it to a dangerous sink like innerHTML, without the server being involved.
Open in the app to mark lessons complete, take notes and track your progress.