[英](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.