sup*_*azy 7 content-security-policy angular unsafe-inline
我想发布一个具有严格内容安全策略的 Web 应用程序。最后剩下的问题是:style-src 'self';
我在浏览器控制台中收到错误消息,指出根据 CSP 中的 style-src 指令阻止加载资源。该错误引用了从 生成的 main..js 文件中的代码ng build --prod
。
如果我添加'unsafe-inline'
到style-src
CSP 中的指令,一切都会正常,但我不想这样做。
我可以在代码或构建选项中做些什么来使 Web 应用程序与更严格的 CSP 配合使用吗?
我使用的是 Angular 11,刚刚升级到 12,但出现了同样的错误。
谢谢!
小智 10
如果此类违规行为相对较少,您可以添加它们的哈希值。例如,如果您在日志中看到以下内容:
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.
Run Code Online (Sandbox Code Playgroud)
添加'sha256-YpcdPia2p132TdnpnY8zwrWWSqByEKGZBY5iqsLBkSg='
您可能还需要'unsafe-hashes'
- 取决于上下文。
注意:这种方法不容易维持。样式的微小变化将迫使您重新创建哈希。仅当您有少量此类内联脚本时它才有用。
您可以使用随机数来“祝福”内联样式并批准它们。然而,即使是提倡 CSP 随机数的 Google 专家通常也不会将它们部署在style-src
- 只部署在script-src
.
注意:这种方法很难部署。需要为每个页面加载生成一个唯一的随机数。
'unsafe-inline'
- 适合style-src
(不太适合script-src
)事实上,即使设置 CSP 也
style-src 'unsafe-inline' 'self' someurl.com;
比 99.9% 的站点安全得多。比accounts.google.com完全没有限制style-src
。
Github拥有出色的高质量 CSPstyle-src: 'unsafe-inline'