Content Security Policy “Refused to execute inline event handler” error

独自空忆成欢 提交于 2020-05-30 09:02:24

问题


I'm trying to mitigate XSS attacks by setting the Content-Security-Policy header but Chrome keeps throwing an error:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-Njg3MGUxNzkyMjViNDZkN2I3YTM3MDAzY2M0MjUxZGEzZmFhNDU0OGZjNDExMWU5OTVmMmMwMTg4NTA3ZmY4OQ=='". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

I tried setting the nonce in <script nonce="Njg3MGUxNzkyMjViNDZkN2I3YTM3MDAzY2M0MjUxZGEzZmFhNDU0OGZjNDExMWU5OTVmMmMwMTg4NTA3ZmY4OQ==" href="main.js"></script> but it does not worked.

Here's my Content-Security-Policy header:

default-src 'none'; 
script-src 'self' 'nonce-NjJjN2E5YjA0ZDJhNDlhZjlhMDFmZjQzMjE4YzhmMTAzOWNjZjVjMGZjNDIxMWU5YWIyNGMwMTg4NTA3ZmY4OQ=='; 
connect-src 'self' https://vimeo.com; 
img-src 'self'; 
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; 
font-src 'self' https://fonts.gstatic.com; 
media-src 'self' http://player.vimeo.com; 
frame-src 'self' http://player.vimeo.com;

I don't like setting the script-src as unsafe-inline, as it voids the used of Content-Security-Policy


回答1:


Your CSP is blocking an inline event handler in your HTML code, like <button onclick="myFunction()">Click me</button>.

Inline event handlers are bad practice (mostly because they are inline). See this answer for insight.

Nonce does not seem to work with inline event handlers though. So the best thing to do would be to replace this event handler with a proper one written in your JS file. If you cannot do that, try adding 'unsafe-hashes' to your script-src.

Kudos for rejecting 'unsafe-inline', it's a shortcut we see way too often, including in production.



来源:https://stackoverflow.com/questions/58652892/content-security-policy-refused-to-execute-inline-event-handler-error

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