(CSP) 内容安全策略。处理从外部库添加的内联样式的方法

Pja*_*yno 7 javascript content-security-policy

有没有办法处理从外部库添加的内联脚本/样式?在我自己的风格中,我只使用随机数,但无法将其添加到外部库。

我使用 tooltip.io,当库尝试运行时出现问题:

function() {
                var n = e("./styles/css/styles.scss")
                  , t = document.createElement("style");
                t.innerHTML = n,
                document.head.appendChild(t)
            }(),
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

有什么方法可以处理此类错误吗?

小智 6

最近,我在一个项目中使用的 Jquery unobtrusive javascript 文件遇到了类似的问题,它在 html 元素 Ul 上添加内联 style="display:none" 所以,我更喜欢哈希方法来允许内联样式,您需要添加样式- src 'self' 'unsafe-hashes' 'sha-256 {sha 哈希字符串}'

如果您在控制台中的 chrome 开发人员工具中使用 chrome,其中显示 csp 违规,则在错误消息的最后一行中,它还会显示 sha-256 字符串,您可以将其添加到内容安全策略标头,以便 csp 允许内联 css 或 js ,这种不安全哈希方法比不安全随机数更好,因为每个请求的随机数需要是唯一的,并且哈希是不可逆的,因此始终只允许内容匹配哈希

我觉得你应该尝试打开在 chrome 中给出错误的页面,看看它是否在控制台错误消息的最后一行显示 sha-256 哈希,如果你想手动生成像 sha-512 这样的哈希,你可以为样式生成哈希处理 ./styles/css/styles.scss 后生成的 .css 并在 csp 属性中添加此哈希,例如

Content-Security-Policy: default-src 'none'; style-src 'self' 'sha-512{Manually generated sha-512}';

Run Code Online (Sandbox Code Playgroud)

您可以使用的最后一个选项是样式 src 中的 unsafe-inline,但您可以尝试使用 unsafe-hashes,这会比 unsafe-inline 更好