Why does my code violate the Content Security Policy?

生来就可爱ヽ(ⅴ<●) 提交于 2020-07-10 09:58:25

问题


I want to defer non-critical css using the following mechanism:

<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

I have the following Content Security Policy:

Content-Security-Policy: default-src 'self'; object-src 'none'; font-src 'self'; base-uri 'self'; connect-src 'self'; manifest-src 'self'; img-src 'self'; script-src 'self' 'nonce-7cc36362-697e-4b28-bdd9-0400d8923894' 'sha256-1jAmyYXcRq6zFldLe/GCgIDJBiOONdXjTLgEFMDnDSM='; style-src 'self'; form-action 'self'; frame-ancestors 'none'; media-src 'self'; report-uri /api/cspviolation

When trying to load and interpret the document, the browser blocks the execution of the onload event handler script because it violates the CSP, which I do not understand because the sha256 of that script is set in the script-src directive.

Any ideas? I've used an online sha256 generator generating the the sha256 set in the CSP. Sadly Chrome does not provide me the sha256 it wants in the console, which I've seen before.


回答1:


Inline event handlers can only be whitelisted with a hash using 'unsafe-hashes' in CSP level 3, but this is not yet well supported in browsers. Check https://www.w3.org/TR/CSP3/#unsafe-hashes-usage for specification and the table in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy for browser compatibility.

You best option is probably to move the script to a separate file and adding an event listener.




回答2:


You're using an inline script ("onload=..."), so either your CSP script-src needs to allow unsafe-inline, or you need to load the script differently.



来源:https://stackoverflow.com/questions/59106051/why-does-my-code-violate-the-content-security-policy

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