在 Content-Security-Policy 中添加哈希:style-src

Adding hashes in Content-Security-Policy: style-src

我刚刚将 Google 翻译的 JavaScript 工具添加到我的项目中。我已经完成并将哈希添加到我的 script-src 并且它正在工作。问题是我仍然在控制台中收到有关无法加载样式的错误,即使我已将哈希添加到 style-src (Chrome)

示例错误消息:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'sha256-+cU/VT0vv47hxLJZovgG53kGPWPopxhXhYgUD6IR5Ro=' 'sha256-2Ohx/ATsoWMOlFyvs2k+OujvqXKOHaLKZnHMV8PRbIc=' 'sha256-qQUBUjasnJdhrNlgzajDJnnOf9HGERy1tkajP7dru0c=' 'sha256-B6LEPigs3viM+y/BwYQU665laXgIDFgp+sr+sdoaJqQ=' translate.googleapis.com 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-qQUBUjasnJdhrNlgzajDJnnOf9HGERy1tkajP7dru0c='), 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.

您可以看到我的 CSP 中已有哈希。

此外,正是以这种方式添加散列处理了我的内联脚本错误消息。

样本HTML:

<!DOCTYPE html>
<html lang="en-US">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 
translate.google.com translate.googleapis.com localhost www.gstatic.com www.google.com 
'sha256-qQUBUjasnJdhrNlgzajDJnnOf9HGERy1tkajP7dru0c=' 
'sha256-+cU/VT0vv47hxLJZovgG53kGPWPopxhXhYgUD6IR5Ro=' ws: wss:; object-src 'none'; 

script-src 'sha256-NNiElek2Ktxo4OLn2zGTHHeUR6b91/P618EXWJXzl3s=' 
'sha256-97l24HYIWEdSIQ8PoMHzpxiGCZuyBDXtN19RPKFsOgk=' 

'sha256-w65k1oeqcYS7ejRz7pWG6X3uKVFzmotHeiJkjIE7LQY=' 
'sha256-qQUBUjasnJdhrNlgzajDJnnOf9HGERy1tkajP7dru0c=' 'self' 
translate.google.com translate.googleapis.com translate-pa.googleapis.com; 

style-src 
'sha256-+cU/VT0vv47hxLJZovgG53kGPWPopxhXhYgUD6IR5Ro=' 
'sha256-2Ohx/ATsoWMOlFyvs2k+OujvqXKOHaLKZnHMV8PRbIc=' 
'sha256-qQUBUjasnJdhrNlgzajDJnnOf9HGERy1tkajP7dru0c=' 
'sha256-B6LEPigs3viM+y/BwYQU665laXgIDFgp+sr+sdoaJqQ=' translate.googleapis.com 'self'; "/>

<body>

<h1>My Web Page</h1>

<p>Hello everybody!</p>

<p>Translate this page:</p>
<Table>
<tr>
<td>
<div id="google_translate_element"></div>
</td>
</tr>
</table>
<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</body>
</html>

我需要更改什么才能摆脱这些内联样式错误消息?

我得出的结论是,虽然向 CSP 添加散列适用于脚本(至少对于 google 翻译),但它不适用于样式。但由于 google 翻译在没有这些样式的情况下也能完美运行,因此控制台中的错误无关紧要。