Overview
Content Security Policy (CSP) is a security mechanism implemented by web browsers that helps prevent cross-site scripting (XSS) and data injection attacks by controlling which resources a user agent is allowed to load for a given page. CSP operates as a policy set by the server through an HTTP header or a <meta> tag, specifying allowed sources for scripts, styles, images, and other content types.
For developers working in secure environments, CSP is a critical tool for mitigating attacks that exploit the trust a browser places in content loaded from a page's origin. It's used extensively in applications that process untrusted input, such as forums, comment systems, and content management platforms, where malicious actors might attempt to inject harmful scripts.

Why It Matters
CSP is essential for modern web applications that must defend against a wide range of client-side attacks. When properly implemented, CSP significantly reduces the risk of XSS by preventing unauthorized scripts from executing, even if an attacker manages to inject malicious code into a page. This is particularly important in environments where user-generated content is processed, as it limits the ability of attackers to exploit vulnerabilities in the application's trust model.
From a compliance perspective, CSP is often required by security standards and regulations such as GDPR, HIPAA, and OWASP Top 10. It also supports content integrity checks, ensuring that scripts and stylesheets loaded by a page have not been tampered with during transit. For developers maintaining large applications, CSP helps enforce consistent security policies across the entire application stack.
How It Works
CSP is implemented through a set of directives that define allowed sources for different resource types. The browser enforces these policies by blocking any resources that do not match the specified sources. CSP directives can be set via an HTTP header or a <meta> tag, with the HTTP header being preferred for performance and security reasons.
- CSP policies are defined by a series of directives such as
script-src,style-src, andimg-src, each controlling a specific resource type. - The
default-srcdirective acts as a fallback for all unspecified directives, helping to enforce a baseline security posture. - CSP directives support a variety of source expressions including
'self','unsafe-inline','unsafe-eval', and specific domains or protocols. - Violations of CSP policies are reported via the
report-uriorreport-todirectives, allowing developers to monitor and debug policy issues without breaking functionality. - Modern browsers support CSP Level 3, which introduces additional directives and enhanced reporting mechanisms for better control and visibility.
Quick Reference
| Item | Purpose | Notes |
|---|---|---|
| script-src | Controls script loading sources | Essential for XSS prevention |
| style-src | Controls stylesheet sources | Prevents unauthorized CSS injection |
| img-src | Controls image sources | Reduces data exfiltration risk |
| default-src | Fallback for unspecified directives | Must be explicitly set for safety |
| report-uri | Specifies violation reporting endpoint | Use with report-to for CSP Level 3 |
Basic Example
This basic example shows how to set a simple CSP policy via an HTTP header that allows scripts from the same origin and any secure HTTPS sources.
Content-Security-Policy: script-src 'self' https:; object-src 'none';
The directive script-src 'self' https: allows scripts to be loaded only from the same origin or via HTTPS, while object-src 'none' blocks all embedded objects. This prevents inline scripts and external script sources, reducing XSS risks.
Production Example
In a production environment, CSP should be carefully configured to balance security with functionality. This example demonstrates a more robust policy that includes reporting, strict script sources, and fallbacks for compatibility.
Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https:; connect-src 'self'; report-uri /csp-violation-report;
This policy allows inline scripts and eval for legacy compatibility, but restricts other resources. It includes reporting to a dedicated endpoint, which helps in monitoring and tuning the policy without breaking user experience. The connect-src directive restricts AJAX requests to the same origin, mitigating potential data leakage.
Common Mistakes
- Overly permissive policies, such as allowing
'unsafe-inline'or'unsafe-eval'without necessity, which negates the security benefits of CSP. - Not setting
default-src, which leaves unspecified resource types vulnerable to attack. - Incorrectly configuring
report-urior missingreport-to, leading to undetected policy violations. - Using CSP with
unsafe-inlinein combination withnonceorhashdirectives, which can cause conflicts and bypass protections. - Not testing CSP in a staging environment before deployment, leading to broken functionality in production.
Security And Production Notes
- Always use the
Content-Security-PolicyHTTP header instead of a<meta>tag for better performance and security. - Implement violation reporting using
report-uriorreport-toto monitor policy effectiveness without breaking functionality. - Use
'self'for all directives unless external resources are absolutely necessary, and validate all external sources. - When using
unsafe-inline, ensure that all inline scripts are properly sanitized or replaced with external scripts. - Test CSP policies thoroughly in staging to prevent unintended blocking of legitimate resources or features.
Related Concepts
CSP is closely related to several core web security concepts. Content Security Policy is part of the broader security headers ecosystem, which includes Strict-Transport-Security and X-Content-Type-Options. Cross-site scripting (XSS) is the primary threat CSP mitigates, making it a key defensive layer in web application security. Nonce and hash are mechanisms used within CSP to allow specific inline scripts without compromising security. HTTP headers are the primary delivery mechanism for CSP, and understanding their behavior is crucial for effective implementation. Finally, web application firewalls (WAFs) often complement CSP by providing additional filtering and protection against malicious content.