React CRA with CSP:拒绝执行内联脚本

React CRA with CSP: Refused to execute inline script

我已经使用 Material UI Create React Template 建立了一个新网站。

我添加了一个内容安全策略,构建成功并部署了,但是页面没有显示在浏览器中,我收到以下错误:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-mB4hl8euSw00eXDUIRf8KeqpMfBXgg0FILGScPTo+n0='), or a nonce ('nonce-...') is required to enable inline execution.

我没有任何内联脚本。

当我将指定的散列添加到我的内容安全策略时,网站可以正常工作,但如果我再次部署,散列会发生变化,我需要使用新的散列更新我的内容安全策略。

哈希从何而来,是否可以避免在部署期间每次都需要手动更新哈希?

Googletagmanager 将内联脚本添加到您的页面。您将无法使用 googletagmanager 强制执行严格的 script-src(没有 unsafe-inline),除非您将其设置如下:https://developers.google.com/tag-manager/web/csp

您可能还需要处理其他动态构建的脚本。

感谢您到目前为止的帮助。我已经找到问题的答案所以我会分享它希望它能帮助其他人。

根据 Create React App 文档中的 Advanced Configuration section

By default, Create React App will embed the runtime script into index.html during the production build.

这似乎是动态构建脚本的来源。

文档进一步建议 INLINE_RUNTIME_CHUNK=false 标志应包含在 .env 文件中以避免嵌入脚本。

通过在 .env 文件中包含 INLINE_RUNTIME_CHUNK=false 标志、重建和部署,我能够解决问题。

对我来说,问题是 script-src 标签是由我的后端 api 提供的,它为反应包提供服务。它显然包含在头盔中间件中,我正在使用它。 一旦我删除它,它就开始工作了。