Skip to content

What is Content-Security-Policy and how does it help?

Short answer

Content-Security-Policy is an HTTP response header that tells the browser which sources of scripts, styles, images, and other content are allowed to load and execute on a page. By disallowing inline script and untrusted origins — ideally via nonces or hashes — it acts as a defense-in-depth backstop that neutralizes injected XSS payloads even when one slips through.

Content-Security-Policy (CSP) is a browser-enforced policy, delivered as an HTTP response header, that constrains what a page is allowed to load and execute. Its main job in practice is to reduce the impact of XSS: even if an attacker injects a <script> tag, a good CSP means the browser simply refuses to run it.

How it works

The server sends a policy made of directives, each naming allowed sources:

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'
  • default-src 'self' — by default, only load resources from the page's own origin.
  • script-src — controls where script may come from. Critically, this can forbid inline script and eval, which is where most XSS executes.
  • object-src 'none', base-uri 'none' — close off Flash/<object> and <base>-tag hijacking.

Nonces and hashes beat domain allowlists

An allowlist of trusted script domains is fragile — many CDNs host vulnerable libraries or JSONP endpoints that let attackers bypass it. A strict CSP instead uses a per-response nonce (a random value the server puts on its own legitimate <script nonce=...> tags) or a hash of allowed inline scripts. An injected script has no valid nonce, so the browser blocks it. This is the modern recommended approach.

Roll it out safely

Content-Security-Policy-Report-Only enforces nothing but reports violations to a collection endpoint, letting you find what would break before turning the policy on. Reporting also surfaces real attack attempts.

Why it is a backstop, not the fix

CSP cannot fix the underlying injection — it limits the blast radius. You still need contextual output encoding as the primary control. CSP is the seatbelt, not a reason to drive recklessly.

Interviewers look for "limits where scripts load/run," nonce/hash over domain allowlists, the Report-Only rollout strategy, and framing CSP as defense in depth rather than a primary control.

Likely follow-ups

  • Why is a nonce-based CSP stronger than an allowlist of domains?
  • What does Content-Security-Policy-Report-Only let you do?
  • Why is CSP a backstop rather than a primary XSS control?

Sources

Get 100 cybersecurity interview questions + answers

Drop your email and we'll send you the free PDF pack and the flashcard deck.

No spam. Unsubscribe anytime.