内容安全策略在桌面上按预期工作,但在移动设备上不工作

Content Security Policy works as expected on desktop but not on mobile

在网站上制定内容安全策略是在网站上提供额外安全层的好方法。

我的内容安全策略在桌面上按预期运行,但在移动设备 (safari) 上会破坏网站。内容安全策略在元标记内。我正在使用随机数和哈希值。在移动设备上,我收到错误消息,指出它拒绝执行内联脚本,因为它违反了包含哈希和随机数的内容安全策略指令。该错误还指出我需要代码中的哈希值或随机数来执行代码,但它们已经存在,这就是它在桌面上运行良好的方式。问题在于,在移动设备上,它的行为就好像哈希值和随机数不存在一样。任何提示表示赞赏。

在 CSP 中,如果您包含 script-srcstyle-src 的随机数,unsafe-inline 将被忽略 如果浏览器理解随机数 。因此,为了与不支持 CSP2 的旧版浏览器兼容(例如,iOS 9 及更早版本上的 Safari),请同时包含您的随机数和 unsafe-inline.

较新的浏览器将遵循随机数并忽略 unsafe-inline。较旧的浏览器不会理解随机数,因此会退回到 unsafe-inline.

https://csp.withgoogle.com/docs/strict-csp.html

script-src nonce-{random} 'unsafe-inline'

The nonce directive means that elements will be allowed to execute only if they contain a nonce attribute matching the randomly-generated value which appears in the policy.

Note: In the presence of a CSP nonce the unsafe-inline directive will be ignored by modern browsers. Older browsers, which don't support nonces, will see unsafe-inline and allow inline scripts to execute.