Buzut
Buzut

Reputation: 5153

Content Security Policy and Google Analytics without unsafe-inline?

Currently, my CSP config in Apache looks like that:

Header set Content-Security-Policy "default-src 'self' 'unsafe-inline' https:"

I'd like to remove the unsafe-inline directive to improve my site's security, see Mozilla's Observatory.

Nevertheless, whenever I remove it, my browser's console shows an error indicating that the inline GA couldn't load…

Is there a workaround?

Upvotes: 3

Views: 5882

Answers (2)

Brian
Brian

Reputation: 25823

As an alternative work-around, you can allow specific, static scripts by adding the script's hash to your content security policy. (A nonce works for dynamic scripts):

  1. Hash your script (e.g., using sha256). Do include white space/capitalization. Don't include the script tags.
  2. Add script-src 'sha256-[MYHASH]' to your content security policy.

See MDN for details. Not supported on IE11 .

Upvotes: 3

Holger Will
Holger Will

Reputation: 7526

Sorry to Edit again. The proposed solution in

New Google Analytics code into external file

did not work for me. instead i got it to work like this:

i add a script tag to my page to load the analytics.js:

<script src="https://ssl.google-analytics.com/analytics.js" async id="ga"></script>
<script src="my_other.js" async></script>

and then in my_other.js file i do this:

window.addEventListener("load", function(){
   ga('create', 'UA-********-1', 'auto');
   ga('send', 'pageview');
})

then in your csp header you have to set some exeption to script-src and image-src. somthing along these lines:

img-src data: 'self' *.google-analytics.com *.g.doubleclick.net;
script-src 'self' *.google-analytics.com

Upvotes: 9

Related Questions