Content Security Policy: A Complete Deep Dive
What Is CSP?
Content Security Policy (CSP) is an HTTP header that tells the browser what sources of content are allowed to load on your page. It's the single most effective defense against Cross-Site Scripting (XSS) attacks when properly configured.
How CSP Works
When a browser receives a CSP header, it creates an allowlist of approved content sources:
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'
Any resource that doesn't match the policy is blocked by the browser before it ever executes.
Common CSP Directives
| Directive | Controls | Example |
|---|---|---|
default-src | Fallback for all resource types | default-src 'self' |
script-src | JavaScript sources | script-src 'self' 'strict-dynamic' |
style-src | CSS sources | style-src 'self' 'unsafe-inline' |
img-src | Image sources | img-src 'self' data: |
connect-src | XHR/Fetch/WebSocket | connect-src 'self' https://api.example.com |
frame-ancestors | Who can embed the page | frame-ancestors 'none' |
Building Your CSP
Step 1: Start in Report-Only Mode
Never deploy CSP enforcement without testing first:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
This sends violation reports without blocking anything.
Step 2: Use 'strict-dynamic' for Modern CSP
For single-page applications, 'strict-dynamic' allows scripts loaded by other trusted scripts to execute:
script-src 'strict-dynamic' 'nonce-{random}' https:
This eliminates the need to maintain a growing allowlist of CDN hosts.
Step 3: Monitor and Iterate
Set up a report-uri or report-to endpoint to collect violations. Over time, you'll discover legitimate resources you missed.
Common CSP Mistakes
- Using 'unsafe-inline' with scripts — This bypasses CSP for inline scripts and makes the policy nearly useless against XSS
- Too permissive —
default-src '*'allows everything from everywhere - Forgotten third-party integrations — Analytics, chat widgets, and CDN scripts often break CSP on first deployment
Testing CSP with Sentinel
Use Sentinel's free header scan to check your CSP configuration:
- Is CSP present?
- Is it missing
'strict-dynamic'? - Does it use
'unsafe-inline'(a red flag)? - Is a
report-uriconfigured?
Summary
CSP is your strongest defense against XSS. Start in report-only mode, use 'strict-dynamic', monitor violations, and iterate. Sentinel can help you audit your CSP in seconds.