Quiz Entry - updated: 2026.07.05
What is Content Security Policy (CSP) and how does it help prevent XSS?
An HTTP header that tells the browser exactly which sources of scripts/styles/images are allowed — so even if an attacker injects a <script>, the browser refuses to run it.
Content Security Policy (CSP) is a browser security mechanism and a defense-in-depth backstop for XSS (it limits damage even when encoding fails).
How it works:
- Server sends
Content-Security-PolicyHTTP header - Header specifies which content sources are allowed
- Browser blocks anything not in the whitelist
What CSP controls:
- Which content types are allowed (scripts, images, styles, etc.)
- Which domains can serve content (domain whitelist)
- Violation reporting to a specified endpoint
XSS protection:
- Blocks inline scripts (unless explicitly allowed)
- Blocks
eval()and similar functions - Prevents loading scripts from untrusted domains
Example header:
Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' 'unsafe-inline'; img-src *
This allows: scripts only from own domain and cdn.example.com, styles from self (including inline), images from anywhere.
Note: Browser must be CSP-compatible to enforce the policy.
See: CSP Evaluator by Google — test your CSP for weaknesses
Go deeper:
MDN — Content Security Policy (CSP) — directives, nonce/hash-based strict CSP, reporting.
OWASP CSP Cheat Sheet — practical CSP policies as XSS defense-in-depth.