Cross-Site Scripting (XSS) remains one of the most common and dangerous website vulnerabilities, allowing attackers to inject malicious code into your website viewed by other users. While developers strive to properly sanitize all user input, mistakes and oversights inevitably happen.
The Content Security Policy (CSP) HTTP header acts as a final, browser-enforced firewall against XSS. CSP is a powerful layer of defense that tells the browser, "only load scripts, images, and other resources if they come from this explicit list of approved sources."
The Core Principle: Whitelisting
A strict CSP operates on the principle of whitelisting. If an attacker successfully injects a malicious script from an unauthorized domain, or tries to run inline JavaScript, the browser simply refuses to run it. This renders the attacker's payload inert, protecting your users even when input sanitization fails.
Key CSP Directives for XSS Prevention
A CSP is composed of one or more directives. The most critical directive for fighting XSS is script-src, which controls the sources from which executable scripts can be loaded.
default-src 'none': This is the strongest starting point. It blocks everything by default, forcing you to explicitly whitelist every resource (scripts, styles, images).script-src 'self' https://trusted-cdn.com: This whitelists scripts loaded from your own domain (`'self'`) and one specific external CDN. Everything else is blocked.- Blocking Inline Scripts: Modern, strict CSPs automatically block inline scripts (alert1) and event handlers (`onclick="..."`). If you must use inline scripts, you should use cryptographic nonces or hashes rather than the insecure `'unsafe-inline'`.
The policy below demonstrates a good, minimal starting point for a secure application:
Example Strict Policy Header
Content-Security-Policy: default-src 'self';
script-src 'self' https://cdnjs.cloudflare.com;
object-src 'none';
base-uri 'none';
form-action 'self';
Action: Only scripts from the current domain or Cloudflare's CDN are allowed to execute.
CSP Simulation: Defense in Action
This simulation demonstrates the power of a strict CSP. Assume the policy above is active. We will try to execute two types of scripts: one from a whitelisted source and one that simulates a malicious injection.
Browser Console Log:
Security Console initialized. CSP is active. Click a button to see the script execution results.
Implementing CSP can be challenging due to legacy code that relies on inline styles or scripts, but the security benefits far outweigh the migration cost. Start with a non-blocking header like Content-Security-Policy-Report-Only to audit your violations before moving to enforcement.