我想发布一个具有严格内容安全策略的 Web 应用程序。最后剩下的问题是:
style-src 'self';
我在浏览器控制台中收到错误消息,指出根据 CSP 中的 style-src 指令阻止加载资源。该错误引用了由
ng build --prod
. 生成的 main..js 文件中的代码
如果我将
'unsafe-inline'
添加到 CSP 中的 style-src
指令,一切正常,但是,我不想这样做。
我可以在代码或构建选项中做些什么来使 Web 应用程序与更严格的 CSP 配合使用吗?
我使用的是 Angular 11,刚刚升级到 12,但出现了同样的错误。
谢谢!
如果此类违规行为相对较少,您可以添加它们的哈希值。 例如,如果您在日志中看到以下内容:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'report-sample'". Either the 'unsafe-inline' keyword, a hash ('sha256-YpcdPia2p132TdnpnY8zwrWWSqByEKGZBY5iqsLBkSg='), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.
添加
'sha256-YpcdPia2p132TdnpnY8zwrWWSqByEKGZBY5iqsLBkSg='
您可能还需要 'unsafe-hashes'
- 根据具体情况而定。
注意:这种方法不容易维持。样式中的一个小变化将迫使您重新创建哈希。 仅当您有少量此类内联脚本时它才有用。
您可以使用随机数来“祝福”内联样式并批准它们。然而,即使是提倡 CSP nonces 的 Google 专家也通常不会将它们部署在 style-src
上 - 只部署在
script-src
上。注意:这种方法很难部署。 需要为每个页面加载生成一个唯一的随机数。 3.使用
'unsafe-inline'
- 对于
style-src
没问题(对于
script-src
不太好)
style-src 'unsafe-inline' 'self' someurl.com;
比 99.9% 的网站安全得多。超过accounts.google.com,根本不限制
style-src
。Github 拥有出色的高质量 CSP,
style-src: 'unsafe-inline'
祝你好运!