用CSP反应CRA:拒绝执行内联脚本 [英] React CRA with CSP: Refused to execute inline script

查看:77
本文介绍了用CSP反应CRA:拒绝执行内联脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用我添加了内容安全策略,该策略已成功构建并部署,但是该页面未显示在浏览器中,并且出现以下错误:

I added a Content Security Policy, built successfully and deployed, however the page doesn't display in the browser and I receive the following error:

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:"script-src'self'".要启用内联执行,需要使用"unsafe-inline"关键字,散列(``sha256-mB4hl8euSw00eXDUIRf8KeqpMfBXgg0FILGScPTo + n0 =')或随机数('nonce -...').

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.

我没有任何内联脚本.

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

When I add the specified hash to my Content Security Policy, the website works, but if I deploy again, the hash changes and I need to update my Content Security Policy with the new hash.

哈希来自哪里,是否有可能避免在部署期间每次都需要手动更新哈希?

Where does the hash comes from and is it possible to avoid needing to update the hash manually each time during deployment?

推荐答案

到目前为止,感谢您的帮助.我已经找到了问题的答案,因此我将与大家分享,希望对其他人有所帮助.

Thanks for your help so far. I have found the answer to the issue so I'll share it in the hope that it helps someone else.

根据Create React App文档中的高级配置"部分:

According to the Advanced Configuration section in the Create React App docs:

默认情况下,Create React App将在生产构建期间将运行时脚本嵌入index.html中.

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

这似乎是动态生成的脚本的来源.

This appears to be the source of the dynamically built scripts.

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

The documents go further to suggest that the INLINE_RUNTIME_CHUNK=false flag should be included in an .env file to avoid the embedding of scripts.

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

By including the INLINE_RUNTIME_CHUNK=false flag in an .env file, rebuilding and deploying, I was able to resolve the issue.

这篇关于用CSP反应CRA:拒绝执行内联脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆