我搜索过并看到很多文章都说内容安全策略如何为我带来好处并保护我的应用程序,但为什么它如此令人沮丧。目前这是我的元标记和我的内容安全策略设置
<meta
http-equiv="Content-Security-Policy"
content="default-src 'none'; script-src 'self' 'unsafe-inline'; connect-src 'self' https://polygon-rpc.com/ https://ipfs.infura.io:5001/api/v0/add?stream-channels=true&progress=false https://ipfs.infura.io:5001/api/v0/* img-src 'self'; style-src 'self' 'unsafe-inline'; base-uri 'self'; form-action 'self'; font-src 'self' https://fonts.gstatic.com;
"
/>
在我的应用程序中,我连接到多边形网络,用户可以将文件上传到 IPFS。现在的问题是,虽然上面允许成功上传文件,但 IPFS 发送上传图像的 url 以向用户显示文件预览,并且每个请求的 url 都会更改,但被 CSP 阻止。所以我现在想知道的是如何完全禁用该死的东西。我不想要它,因为如果我必须手动添加所有外部网站,我会调用元标记。这似乎很愚蠢我尝试使用它从服务器端设置内容安全策略,但它似乎没有做任何事情,只有来自 react html 文件中的元标记的设置才有效。
app.use(
contentSecurityPolicy({
useDefaults: true,
directives: {
defaultSrc: ["'none'"],
connectSrc: [
"'self'",
"https://polygon-rpc.com/",
"https://ipfs.infura.io:5001",
"https://ipfs.infura.io:5001/api/v0",
"https://ipfs.infura.io",
],
upgradeInsecureRequests: [],
},
reportOnly: false,
})
);
它是一个托管在 heroku 上的 MERN 应用程序。那么知道如何去做吗?谢谢
最佳答案
I tried setting the content security policy from the server side using this, but it does not seem to do anything and only the settings from the meta tag in the react html file that works.
因此,您有 2 个 CSP 同时作用 - 来自元标记和来自 HTTP header 。所有源都必须通过两个 CSP,因此将应用来自两个 CSP 的最严格规则。
使用元标记或 HTTP header 。
IPFS sends the url of the uploaded image to show the file preview to the user and the url changes on every request but that is blocked by CSP.
设置
img-src *
就够了允许来自任何主机的图像。备注 您在元标记中的 CSP 中有 2 个错误:
;
之前 img-src 'self';
.将其修复为 ; img-src * data: blob:;
允许来自任何来源的图像,包括 data:-Urls 和 blob:-Urls。 https://ipfs.infura.io:5001/api/v0/*
来源错误,因为 CSP 不支持 *
在路径部分。删除 *
. 关于html - 如何在 react 中禁用内容安全策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69634749/