How to fix 'because it violates the following content security policy directive'

Stuart Larsen · #article7 years ago

Blocked by Content Security Policy

'csp error because it violates the following content security policy directive'

Content Security Policy error message

'because it violates the following content security policy directive' is a browser error message that occurs when Content Security Policy is blocking a resource from loading.

Why is Content Security Policy blocking my resource?

Content Security Policy blocks all resources that don't match it's policy. To view the policy for a specific website use the CSP Evaluator.

Here is an example Content Security Policy:

What is being blocked?

The specific resource being blocked is described in the error message. Some examples of content being blocked:

  • Refused to load the script 'https://cdn.mycompany.com/scripts.js' because it violates is stating that the script https://cdn.mycompany.com/scripts.js was blocked from being downloaded and executed.
  • Refused to execute inline script because it violates means that inline Javascript was blocked. Inline javascript includes <script> tags and onevent handlers <button onclick="doThing()">
  • Refused to apply inline style because it violates means an inline CSS was blocked. This could be either <style> tags or an inline style attribute <div style="font-size: 12px">

How to fix?

Inline Resources

If the blocked resource is an inline resource, the inline resource should be moved to it's own file.

External Resources

If the blocked resource is an external file, it should be added to the policy. For example above, if we had the error message Refused to load the script 'https://cdn.mycompany.com/scripts.js' because it violates the following directive 'script-src', we need to add "https://cdn.mycompany.com/script.js" to the "script-src" directive of the policy. There are tools that can automatically generate policies such as CSP Generator.

To check if your policy is constructed correctly you can use the Policy Evaluator tool.

What if I have a lot of these errors?

There's automatic tools for generating a new policy that includes all the external resources:

Content Security Policy (CSP) Generator

The inline resources still need to moved to their own files manually.

What if I'm worried about Content Security Policy breaking my website in production?

Content Security Policy includes a mechanism called "report-uri" that alerts website owners when something is blocked.

Csper is a tool (report-uri) that collects these alerts and gives you insight on where the alerts are occurring and how to fix the issues quickly. It also provides aggregation, analysis, alerting and more.

Looking for tools to make CSP easier?

Csper has the tools to help you understand, deploy and manage your content security policy. Get started in minutes. Report aggregations, classification, analysis, alerting, realtime and more. Free 14 day trial.