Introduction
The CSP stands for Content-Security-Policy. It provides a security layer to the web application and helps to mitigate attacks ranging from XSS (Cross-site Scripting) to clickjacking.
Using CSP, we can control what resources can be loaded on the page and reject all disallowed resources to protect the web application.
To enable CSP in the web application, you need to specify the CSP in the HTTP header:
Content-Security-Policy: policy
When responding to the client, you can inject this HTTP header into the response.
You can find CSP everywhere. The above image is one of the API calls from LinkedIn and we can find the CSP implementation there.
The CSP defines different directives for controlling different resources:
default-src: default policy for JavaScript, Image, Style, etc.
script-src: define policy for JavaScript
style-src: define policy for CSS
img-src: define policy for images
…
Examples
When specifying default-src in the policy, it is a fallback policy for other resource types that are not specified in the CSP.
The following policy means the web application only accepts the resource from the website’s own origin.
Content-Security-Policy: default-src 'self'
In modern software development, it is common to integrate third-party services into the application. So, we might need to load resources from their server. To achieve this, we can specify the trusted domain in the policy:
Content-Security-Policy: default-src 'self' example.com *.example.com
After implementing CSP, if any user wants to load disallowed resources to your website, they will receive an error like this. You can also adjust the CSP to report violations.
Report Violations
By default, the CSP does not report violations. If there is any violation, you will not aware of that. When implementing CSP, you always want to adjust the policy from time to time. Because your application might integrate with a bunch of external services and you want to observe those domains.
To achieve violation reporting, the CSP provides two approaches:
Content-Security-Policy-Report-Only
When using this mode, any violation will be reported to the URL that you specified and does not block anything.
Specify report-uri directive in Content-Security-Policy
When using this mode, any violation will be submitted to the URL that you specified.
Now, the website owner is able to receive violation reports and decide whether the resources should be blocked or allowed.
For details of CSP, please refer to: