[英](CSP) Content Security Policy. Way to handle inline styles added from external liblary
有没有办法处理从外部库添加的内联脚本/样式? 在我自己的 styles 中,我只使用随机数,但无法将其添加到外部库。
我使用 tooltip.io 并在库尝试运行时出现问题:
function() {
var n = e("./styles/css/styles.scss")
, t = document.createElement("style");
t.innerHTML = n,
document.head.appendChild(t)
}(),
CSP 显示
[Report Only] Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'nonce-b123d558a63bc7e84aa7' ". Either the 'unsafe-inline' keyword, a hash ('sha256-SamqqFx+xVKq8AnoIWgeammNlDl/h4AP94HthfQO43Q='), or a nonce ('nonce-...') is required to enable inline execution.
有没有办法处理这种错误?
Recently I faced the similar issue for Jquery unobtrusive javascript file I used in one of project it was adding inline style="diplay:none" on html element Ul So, I prefered Hash approach to allow inline style in this you need to add style- src 'self' 'unsafe-hashes' 'sha-256 {sha hashed string}'
如果您在显示 csp 违规的控制台中的 chrome 开发人员工具中使用 chrome,则在错误消息的最后一行还显示 sha-256 字符串,您可以将其添加到您的内容安全策略 header,以便 csp 允许内联 css 或 js ,这种不安全的哈希方法比不安全的随机数更好,因为随机数需要每个请求都是唯一的,并且 hash 是不可逆的,所以内容匹配 hash 只允许始终
I feel you should try to open your page which gives error in chrome and see if it shows sha-256 hash as last line in console error message, if you want to manually generate hash like sha-512, you can generate hash for the styles ./styles/css/styles.scss 处理后生成的.css 并将此 hash 添加到 csp 属性中,如
Content-Security-Policy: default-src 'none'; style-src 'self' 'sha-512{Manually generated sha-512}';
您可以使用的最后一个选项是样式 src 中的 unsafe-inline 但您可以尝试使用 unsafe-hash,这将比 unsafe-inline 更好
您必须在 html 的头部指定允许的内容。
要允许内联 styles:
Content-Security-Policy: style-src 'unsafe-inline';
上述内容安全策略将允许像元素一样内联 styles,以及任何元素上的样式属性:
<style>
#inline-style { background: red; }
</style>
<div style="display:none">Foo</div>
您可以使用 nonce-source 仅允许特定的内联样式块:
Content-Security-Policy: style-src 'nonce-2726c7f26c'
您必须在元素上设置相同的随机数:
<style nonce="2726c7f26c">
#inline-style { background: red; }
</style>
或按域:
Content-Security-Policy: style-src https://example.com/
要允许内联脚本和内联事件处理程序:
Content-Security-Policy: script-src 'unsafe-inline';
上述内容安全策略将允许内联元素
<script>
var inline = 1;
</script>
您可以使用 nonce-source 仅允许特定的内联脚本块:
Content-Security-Policy: script-src 'nonce-2726c7f26c'
您必须在元素上设置相同的随机数:
<script nonce="2726c7f26c">
var inline = 1;
</script>
或按域:
Content-Security-Policy: script-src https://example.com/
我将回答我给予赏金的问题。 我认为使库与 CSP 一起工作的唯一方法是向 CSP 添加 nonce 选项。 并在库中添加对带有 nonce 的 CSP 的支持。 为此,库将需要使用该随机数更改所有带有<style>
标记的内联样式。
jsLibrary({
nonce: '<XXXX>'
});
<style nonce="<XXXX>">
</style>
如果您知道任何其他将 CSP 与 3rd 方库一起使用的方法,并且可以在服务器上进行最少的修改,请随时添加答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.