5

I'm using Drupal 8, and I currently use

Header always set Content-Security-Policy "default-src 'self'; nosniff"

However, this causes bugs, such as Google Analytics not working and the textbox mysteriously disappearing from the Edit page. What should I do?

3

The policy needs to contain every domain where assets are loaded from, which will vary depending on which services your site uses such as a CDN or third party JavaScript widgets.

For Google Analytics, it must be able to connect to www.google-analytics.com, and stats.g.doubleclick.net if Display Features tracking is enabled.
The Google Analytics module also requires the unsafe-inline policy value, since it injects the analytics snippet directly on the page.
Googalytics is an alternative built specifically for Drupal 8 that works without unsafe-inline.

Core also currently requires 'unsafe-inline' for scripts in element attributes due to its use of CKEditor 4 (see https://www.drupal.org/project/drupal/issues/2789139)


In order to test a Content Security Policy without impacting the functionality of your site, first use the Content-Security-Policy-Report-Only header instead. This will make the browser report violations of the policy in the browser console and to the report-uri address, without blocking the content on the page. Once you have a policy that works without violations, change the header to Content-Security-Policy.

You can also provide both headers at the same time, allowing you to test changes without the risk of breaking functionality.

Report-uri.io provides a free logging service that you can use to collect violations of both your enforced and report-only rules, and audit for any changes you may need to make.
They also have a wizard utility to help setup your policy for the first time.


Setting up a policy in Drupal 8 is also easier with the Content Security Policy module. It integrates with Drupal 8's libraries system to automatically add script and style sources, provides an admin UI that validates your settings, provides a local handler for report violations, and will apply some optimizations to shorten the policy if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy