Course contentsShow
← Software Engineering
Lesson 1072 of 1,93332. Security EngineeringFree lesson

Content Security Policy (CSP)

Controlling which resources browsers can load, mitigating XSS and injection attacks through CSP headers.

Content Security Policy (CSP)

You'll learn how CSP headers protect your web application by controlling which resources browsers are allowed to load.

The Core Idea

Content Security Policy is a browser security mechanism that lets you declare which sources of content are trustworthy for your site. By setting CSP headers on your HTTP responses, you tell the browser: "Only execute scripts from these domains, load images from those sources, and connect to these APIs." If an attacker manages to inject malicious code, the browser will refuse to execute it because it violates your policy.

Think of CSP as a whitelist bouncer at your website's door. You give the bouncer a guest list (your CSP policy), and they only let in resources from approved sources. Even if someone sneaks malicious JavaScript into your HTML through an XSS vulnerability, the browser bouncer checks the list and blocks it.

How It Works

You configure CSP via HTTP headers:

Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; img-src *

This policy means:

  • default-src 'self': By default, only load resources from your own origin
  • script-src 'self' https://trusted-cdn.com: Scripts can only come from your domain or the trusted CDN
  • img-src *: Images can load from anywhere

Defense Against XSS and Injection

CSP is particularly powerful against XSS attacks. Even if an attacker injects <script>alert('hacked')</script> into your page, the browser won't execute it if inline scripts aren't in your policy. CSP also mitigates data exfiltration by controlling where resources can be sent.

Key Takeaway: Content Security Policy acts as a browser-enforced whitelist that blocks unauthorized resource loading, providing a robust defense layer against XSS and injection attacks even when other protections fail.