Modernizr Causes Content Security Policy (CSP) Violation Errors

痞子三分冷 提交于 2019-11-30 11:49:48

问题


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:

  1. Modernizr support for CSP
  2. Visual Studio support for CSP. Note that browser link does not work if you have CSP enabled as it uses inline JavaScript.
  3. 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.

回答1:


I suspect there's no other solution than to rewrite the parts of Modernizr that use inline code or dynamically evaluated code (which applies to both JS and CSS). The experiences of AngularJS ngCsp might be useful here.




回答2:


I found a fix without having to use unsafe-inline.

You can modify the unminimized Modernizr at one line:

fakeBody = body || document.createElement('body');

convert to

fakeBody = document.createElement('body');

works on IE9, Firefox, and Chrome.



来源:https://stackoverflow.com/questions/26532234/modernizr-causes-content-security-policy-csp-violation-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!