Introduction to Content Security Policy
Content Security Policy (CSP) is a security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. It works by allowing you to specify which sources of content are trusted and can be loaded on your website.
Why CSP Matters
Without CSP, attackers can inject malicious scripts into your pages. These scripts can steal user data, hijack sessions, or redirect users to malicious sites. CSP provides an additional layer of defense by telling browsers exactly which resources are allowed to load.
How CSP Works
CSP is implemented through an HTTP response header. When a browser receives this header, it enforces the policy by blocking any resources that violate the rules you have defined.
A basic CSP header looks like this:
Content-Security-Policy: default-src 'self'
This policy tells the browser to only load resources from the same origin as the page itself.
Key CSP Directives
CSP uses directives to control different types of resources:
- default-src - Fallback for other directives
- script-src - Controls JavaScript sources
- style-src - Controls CSS sources
- img-src - Controls image sources
- connect-src - Controls fetch, XHR, and WebSocket connections
- font-src - Controls web font sources
- object-src - Controls plugins like Flash
- frame-src - Controls iframe sources
Getting Started with CSP
Start with a report-only policy to identify what would be blocked without actually breaking your site:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
Once you have reviewed the reports and adjusted your policy, switch to enforcement mode by using the Content-Security-Policy header.
Test Your CSP
Use our free CSP analyzer to check your current policy and get recommendations for improvement.