I have a web app using the default html5boilerplate Content Security Policy.
However, we have the new Google analytics.js snippet on the page, which is being blocked by the CSP.
I've been trying to find an example of a CSP and JS include structure that will allow Google analytics.js, but haven't had any luck.
The closest SO post is Google Analytics and Content-Security-Policy header, but this is using the older ga.js.
Unfortunately the Google Docs don't mention CSP.
I've reached the following solution though:
Bottom of my html file:
<script type="text/javascript" src="/js/analytics.js"></script>
Content of analytics.js:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function()
{ (i[r].q=i[r].q||[]).push(arguments)}
,i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g; m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');
.htaccess CSP:
Header set Content-Security-Policy "script-src 'self' https://ssl.google-analytics.com http://www.google-analytics.com; object-src 'self'"
This works - but I'm unsure if I will have broken the asyncronous nature of the GA code, or caused some other unintended consequence.
Can someone advise the correct way to allow Google analytics.js through a Content Security Policy?
Author Edit: In the end I used the solution detailed in Google Analytics and Content-Security-Policy header, reverting back to ga.js. But I'd still like to know if it's possible to use analytics.js in the same way.
Author Edit 2: Looks like it may be possible using analytics.js direct from Google and the same principles as the other SO post:
Bottom of HTML file:
<script type="text/javascript" src="https://ssl.google-analytics.com/analytics.js"></script>
<script type="text/javascript" src="/js/analytics.js"></script>
Contents of analytics.js:
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
CSP:
Header set Content-Security-Policy "script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com; object-src 'self'"
This is untested - I've not checked if Google analytics is receiving data, but there are no console or CSP errors. Fingers crossed.
your .htaccess solution should be all correct.
why should you brake the (clientside) asynchronous nature of it ?
in the browser console you will see which requests to which hosts are blocked, if there are any blocked request from gugl while surfing the page you can add the hostname to your policy-setting