如何将 nonce 属性随机 id 与内联关联 JavaScript

How to associate nonce attribute random id with inline JavaScript

我要在网站上添加 Content-Security-Policy 限制。所以内联 JS 和 CSS 不再可用。但是我应该在每个页面上都有一些内联 JS,因此我添加了 nonce 属性。 我应该为页面上的每个内联脚本和 css 生成新的随机 ID

<html>
<head>
<script src="url/example1.js" nonce="id-1"/>
<script src="url/example2.js" nonce="id-2"/>
<script src="url/example3.js" nonce="id-3"/>
</head>
</html>

或者我可以生成一个 id 并为页面上的每个 JS 和 CSS 重复使用它(是否像上面的方法一样安全)?

<html>
<head>
<script src="url/example1.js" nonce="id-1"/>
<script src="url/example2.js" nonce="id-1"/>
<script src="url/example3.js" nonce="id-1"/>
</head>
</html>

对我来说,这两种方法都很好,但 CSP header 有长度限制(1024 个字符)。每个 id 看起来都像 'nonce-{20..30 chars}'。存在下一个新的内联 JS 可能被拒绝的风险...

https://www.w3.org/TR/CSP3/#security-nonces 表示每次提交保单时都应生成一个唯一值。这意味着您可以在整个文档中重复使用随机数。在下一页加载时,您需要一个新的随机数。