Content Security Policy (CSP)
Last Updated :
23 Jul, 2025
Websites are the prime targets for cyberattacks, and one of the most prevalent vulnerabilities is Cross-Site Scripting (XSS). To combat such threats, website developers must implement strong security protocols, one of which is the Content Security Policy (CSP). CSP is a security feature that helps to prevent attacks like XSS by controlling the sources from which content can be loaded.
What is Content Security Policy (CSP)?
Content Security Policy (CSP) is a browser feature that helps mitigate a wide range of attacks by specifying which sources of content are allowed to be loaded on your web pages. It is designed to protect your site from various forms of malicious activity, particularly XSS attacks, where malicious scripts are injected into web pages to steal sensitive information or perform unwanted actions.
The core idea of CSP is to define rules, known as directives, that tell the browser where it can load resources such as JavaScript, images, CSS files, and media. By doing so, CSP helps ensure that only trusted sources can load content on your website.
Syntax:
In a CSP operating system, syntax consists of directives that describe content permissions and their sources. The syntax is as follows:
Content-Security-Policy: policy-directive; policy-directive; ...
Every directive means a specific resource or task that happens on the webpage. Here are some common directives:
- Default-src: Sets the default sources for all content on the page (scripts and styles).
- Script-src: Points out where JavaScript can originate from.
- Style-src: Establishes the sources that can bring stylesheets.
- img-src: Designates where images can be obtained from.
- Connect-src: Identifies approved origins for network requests (such as AJAX and WebSocket).
- object-src: Closes off plugin sources such as <object>, <embed>, or <applet>.
- font-src: Identifies the origins allowing loading of font files.
- Media-src: Oversees sound and video content resources.
- Frame-src: Limits the frame sources to those authorized in embedded frames such as <iframe>.
Example CSP:
Content-Security-Policy: default-src 'self'; script-src 'self'
https://apis.example.com; img-src 'self' data:;
Here’s how the policy works:
- Default-srcScript-src 'self': All content has to be fetched from the same domain as that which hosted the HTML page.
- Script-src 'self' https: An API service (https://apis.example.com) serves as the only source for JavaScript loaded on the website.
- img-src 'self' data: One can retrieve images from their origin or represent them as data URIs.
How Does It Work?
CSP acts as another barrier to protecting websites. Here's a breakdown of how it works:
- HTTP Request: A request goes from the user’s browser to the server for loading a page. After the server replies with content security policy information.
- Policy Enforcement: The browser reviews the CSP policies and executes the regulations. While loading the page all resources (script images styles) are scrutinized against the policy.
- If the source of the resource matches an approved domain the browser enables it to be loaded.
- Should the source of the resource mismatch be the one specified in the policy the browser prevents its loading and marks a warning in the browser logs.
- Content Execution: The functionality of inline scripts is supervised by CSP along with the source of JavaScript. By default, assessors disable inline scripts unless they receive explicit approval via a nonce or hash.
- Violation Reporting: In case a report-uri directive is present in the CSP the browser delivers specifics on blocked resources to the indicated URI. Developers gain valuable information to adjust their policies.
Nonces and Hashes
To enable inline scripts or styles, CSP provides two mechanisms: nonces and hashes.
- Nonces: An arbitrary string (nonce) is included in scripts and styles. To enable the inline content the browser checks if the nonce listed in the CSP header confirms with the nonce identified in the script or style. Example:
Content-Security-Policy: script-src 'nonce-abc123';
In the HTML:
HTML
<script nonce="abc123">
console.log('This script is allowed because it has a matching nonce.');
</script>
- Hashes: To permit a particular inline script you may utilize its hash of the content. The browser analyses the hash of the inline script and matches it against the one in the CSP. Example:
Content-Security-Policy: script-src 'sha256-x1y2z3...';
Example
We will analyze a situation in which you oversee a website and wish to enforce protection protocols.
Protecting Against XSS
Your purpose is to stop third-party scripts from executing on your platform. Your server includes a CSP header that looks like this:
Content-Security-Policy: default-src 'self'; script-src 'self'
https://cdn.trusted.com/; style-src 'self' 'unsafe-inline';
This policy:
- Blocks access to all resources by default on the current domain.
- Allows JavaScript to load only from your domain or the trusted CDN (https://cdn.trusted.com/).
- Enables inline styles even though their use should be moderate due to the danger of introducing risks if poorly controlled.
- Should an outside script take root the browser stops it immediately to safeguard against the XSS issue.
Reporting Violations
In case you want to monitor violations of the CSP, you can specify a reporting endpoint:
Content-Security-Policy: default-src 'self'; report-uri /csp-report;
A report will be sent to the /csp-report address by the browser whenever a violation happens (such as an unauthorized script loading). You can observe and resolve possible security threats through this.
Benefits of CSP
- Reduces XSS risks: By regulating where scripts and resources are fetched from CSP lowers the danger of executing malicious code.
- Protects against clickjacking: By implementing frame-ancestors directives you can avoid allowing other domains to frame your site and prevent clickjacking assaults.
- Improves site security posture: CSP encourages developers to thoughtfully assess and constrain the origins of content creating a safer website.
Conclusion
As a key web security framework developers can use CSP to shield their websites from numerous threats such as Cross-Site Scripting (XSS) and data injection attacks. By setting firm rules for the content loaded and executed on a webpage CSP provides an effective shield against security threats.
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics