内容安全策略“拒绝执行内联事件处理程序”错误

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

我试图通过设置 Content-Security-Policy header 来减轻 XSS 攻击,但 Chrome 一直抛出错误:

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.

我尝试在 <script nonce="Njg3MGUxNzkyMjViNDZkN2I3YTM3MDAzY2M0MjUxZGEzZmFhNDU0OGZjNDExMWU5OTVmMmMwMTg4NTA3ZmY4OQ==" href="main.js"></script> 中设置随机数,但它不起作用。

这是我的 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;

我不喜欢将 script-src 设置为 unsafe-inline,因为它会使 Content-Security-Policy

的使用无效

您的 CSP 正在阻止 HTML 代码中的内联事件处理程序,例如 <button onclick="myFunction()">Click me</button>

内联事件处理程序是不好的做法(主要是因为它们是内联的)。 请参阅 了解见解。

Nonce does not seem to work with inline event handlers 不过。因此,最好的办法是用在您的 JS 文件中编写的适当的事件处理程序替换此事件处理程序。 如果您做不到,请尝试将 'unsafe-hashes' 添加到您的 script-src.

感谢拒绝 'unsafe-inline',这是我们经常看到的捷径,包括在生产中。

此错误也可能由内联样式(<style> </style> 内 html 文件中的样式)引起。 我遇到了这个问题,删除内联样式解决了问题。

Angular 用户可以通过将每个配置的“inlineCritical”设置为 false 来解决此问题(更多详细信息 here)。

示例:

"configurations": {
 "production": {
   "optimization": {
     "scripts": true,
     "styles": {
       "minify": true,
       "inlineCritical": false
     },
     "fonts": false
   }
 }

}