I am attempting to use the new Content Security Policy (CSP) HTTP headers on a test site. When I use CSP in conjunction with Modernizr I get CSP violation errors. This is the CSP policy I am using:
Content-Security-Policy: default-src 'self'; script-src 'self' ajax.googleapis.com ajax.aspnetcdn.com; style-src 'self'; img-src 'self'; font-src 'self'; report-uri /WebResource.axd?cspReport=true
These are the errors from the Chrome browser console:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'".
Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
window.Modernizr.injectElementWithStyles - modernizr-2.7.2.js:134
window.Modernizr.tests.touch - modernizr-2.7.2.js:457(anonymous function)
modernizr-2.7.2.js:949(anonymous function) - modernizr-2.7.2.js:1406
I discovered the following workaround on the Github Modernizr site. However, the workaround was first put forward in March and doing a little Google-Fu I can find no fixes or workarounds to this issue.
I know that I can include the unsafe-inline directive which can get around this error but this also enables unsafe code to run and negates the use of CSP in the first place. Does anyone have any solutions?
Update - What is CSP
CSP is a HTTP header supported by all major browsers (Including Edge). Essentially its a white list of content the browser is allowed to use to render the page. Find out more here or read Mozilla's documentation for CSP here and here.
Update - Help Highlight CSP
CSP is now available on all browsers (Edge added support, yay!) and its a gigantic leap forward in web security. For those interested in getting more third party support for CSP, see these:
- Modernizr support for CSP
- Visual Studio support for CSP. Note that browser link does not work if you have CSP enabled as it uses inline JavaScript.
- Visual Studio Web Essentials Extension support for CSP. Web Essentials is a Visual Studio addin, whose features often end up in the next version of Visual Studio.