Content Security Policy (CSP)
You'll learn how Content Security Policy headers allow you to control which resources your web application can load and execute, making XSS attacks much harder to pull off.
What Is CSP?
Content Security Policy is like a bouncer at a nightclub—it maintains a whitelist of trusted sources and blocks anything that doesn't match. Instead of trying to sanitize every piece of content (which you've learned about), CSP takes a defense-in-depth approach by telling the browser, "Only run scripts from these approved locations, and ignore everything else."
When you set a CSP header on your web server, the browser enforces those rules. Even if an attacker manages to inject malicious code into your page (through reflected, stored, or DOM-based XSS), the browser will refuse to execute it if it violates your policy.
How CSP Works
You define a CSP using HTTP response headers. The most critical directive is script-src, which controls where JavaScript can be loaded from:
Content-Security-Policy: script-src 'self' https://trusted-cdn.com
This policy says: "Only execute scripts from our own domain ('self') and from https://trusted-cdn.com." Inline scripts (like <script>alert('XSS')</script>) and eval() are blocked by default unless explicitly allowed.
Defense Against XSS
CSP dramatically reduces XSS impact. Even if an attacker injects <script> tags, the browser won't execute them unless they come from whitelisted sources. This turns many successful XSS attacks into failed attempts.
You can also use default-src, style-src, img-src, and other directives to control styles, images, and more—building a comprehensive security perimeter.
Key Takeaway:
Content Security Policy acts as browser-enforced access control for resources, restricting script execution to whitelisted sources and providing a powerful defense layer against XSS attacks even when injection occurs.