What is Content Security Policy?
You'll learn what CSP is and how it acts as a security layer to protect your web application from injection attacks.
The Security Gatekeeper
Content Security Policy (CSP) is an HTTP security header that tells the browser exactly which resources (scripts, styles, images, etc.) are allowed to load on your page. Think of it as a bouncer at a club with a strict guest list — only approved sources get through the door.
Without CSP, if an attacker manages to inject malicious code into your site (through XSS or other means), the browser will happily execute it. CSP changes this by defining a whitelist of trusted sources, so even if malicious code somehow appears in your HTML, the browser will refuse to run it.
How CSP Prevents Attacks
Cross-Site Scripting (XSS): CSP blocks inline scripts and eval() by default, forcing all JavaScript to come from approved external files. This makes most XSS attacks ineffective.
Injection Attacks: By controlling which domains can serve content, CSP prevents attackers from loading malicious resources from unauthorized servers.
Unauthorized Resource Loading: Want to ensure images only load from your CDN? CSP lets you specify that, preventing data exfiltration through malicious image requests.
The Real-World Impact
When you implement CSP, you're adding a browser-enforced security policy. Even if your code has vulnerabilities, the browser becomes a second line of defense. It's particularly valuable for sites that embed third-party content or analytics scripts, because you can explicitly control what those scripts are allowed to do.
Key Takeaway: Content Security Policy is a browser security mechanism that whitelists trusted content sources, dramatically reducing the risk of XSS, injection attacks, and unauthorized resource loading by blocking anything not on your approved list.