问题描述
我知道有很多类似的问题,但是我很难弄清楚这个问题,经过数小时的搜索和编辑代码,我无法解决它。
我已经建立了一个MERN堆栈网络应用,并在index.html中添加了脚本“ https://apis.google.com/js/platform.js”以使用Google身份验证。但是将我的应用程序部署到heroku后,出现以下错误:
errors image
Refused to load the script 'https://apis.google.com/js/platform.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set,so 'script-src' is used as a fallback.
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-eE1k/Cs1U0Li9/ihPPQ7jKIGDvR8fYw65VJw+txfifw='),or a nonce ('nonce-...') is required to enable inline execution.
我已经多次编辑代码,最终版本如下所示:
(基于this answer)
index.html
<head>
<Meta charset="utf-8" />
<Meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta name="theme-color" content="#000000" />
<Meta name="description" content="Web site created using create-react-app" />
<Meta http-equiv="Content-Security-Policy"
content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com/js/platform.js ">
<link rel="manifest" href="/manifest.json" />
<link rel="shortcut icon" type="image/png" href="/logo.png">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
manifest.json
{
"short_name": "React App","name": "Create React App Sample","icons": [
{
"src": "logo.png","sizes": "64x64 32x32 24x24 16x16","type": "image/png"
},{
"src": "logo192.png","type": "image/png","sizes": "192x192"
},{
"src": "logo512.png","sizes": "512x512"
}
],"start_url": ".","display": "standalone","theme_color": "#000000","background_color": "#ffffff","content_security_policy": "default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com/js/platform.js "
}
任何帮助将不胜感激。
解决方法
我认为您必须使用Helmet,它必须为您设置CSP标头。您可以将其从快递服务器中删除,并检查是否引起问题。
您可以使用以下代码设置最适合您的网站的CSP标头。
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],scriptSrc: ["'self'","example.com"],objectSrc: ["'none'"],upgradeInsecureRequests: [],},})
);