創建一個簡單的模板電子應用程式。我想對我的 api 執行提取請求,但不斷被內容安全策略錯誤阻止,我不知道如何修復它們。
拒絕連接到“https://api.myapp.com/”,因為它違反了以下內容安全策略指令:“default-src 'self' 'unsafe-inline' data:”。請注意,'connect-src' 未明確設定,因此 'default-src' 用作后備。
索引.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-eval' ">
<meta charset="UTF-8">
</head>
<body>
<div id="root"></div>
</body>
</html>
應用程式.js
const handleSubmit = async () => {
const response = await fetch("https://api.myapp.com/books", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response.json();
};
我嘗試將 api 地址添加到現有策略,并添加其他策略,但沒有任何效果。
uj5u.com熱心網友回復:
在違規訊息中,您有一個白名單:拒絕連接到...以下內容安全策略指令:“ default-src 'self' 'unsafe-inline' data:”。
但是在元標記中,您顯示了一個不同的白名單:default-src 'self' 'unsafe-eval'。
這意味著您至少有 2 個 CSP 正在運行。多個 CSP 充當一致的過濾器 - 所有旨在被允許的源都應通過所有過濾器。因此,應用了所有 CSP 中最嚴格的規則。
弄清楚您在哪里發布第一個 CSP 并將其添加connect-src https://api.myapp.com到其中。并洗掉元標記中的 CSP。
很可能是某個包通過 HTTP 標頭(如何檢查)發布了他的默認 CSP ,因此Helmet受到懷疑 - 它自 v4.1 起發布默認 CSP。
當然,您可以使用以下代碼直接發布 CSP HTTP 標頭:
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({ responseHeaders: Object.assign({
...details.responseHeaders,
"Content-Security-Policy": [ "default-src 'self' 'unsafe-inline' data:" ]
}, details.responseHeaders)});
});
uj5u.com熱心網友回復:
我找到了這個問題的答案。似乎 Webpack 為開發人員模式使用了默認的內容安全策略,可以在 package.json 中覆寫該策略。
取自 webpack WebpackPluginRendererConfig
/**
* Sets the [`Content-Security-Policy` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
* for the Webpack development server.
*
* Normally you would want to only specify this as a `<meta>` tag. However, in development mode,
* the Webpack plugin uses the `devtool: eval-source-map` source map setting for efficiency
* purposes. This requires the `'unsafe-eval'` source for the `script-src` directive that wouldn't
* normally be recommended to use. If this value is set, make sure that you keep this
* directive-source pair intact if you want to use source maps.
*
* Default: `default-src 'self' 'unsafe-inline' data:;`
* `script-src 'self' 'unsafe-eval' 'unsafe-inline' data:`
*/
devContentSecurityPolicy?: string;
通過在 package.json 中設定 devContentSecurityPolicy,我可以設定我自己的內容安全策略。
"plugins": [
[
"@electron-forge/plugin-webpack",
{
"mainConfig": "./webpack.main.config.js",
"devContentSecurityPolicy": "connect-src 'self' https://api.myapp.com 'unsafe-eval'",
"renderer": {
"config": "./webpack.renderer.config.js",
"entryPoints": [
{
"html": "./src/index.html",
"js": "./src/renderer.ts",
"name": "main_window"
}
]
}
}
]
]
注意:更改此設定并保存不會更新應用程式中的策略。您需要停止并再次運行“npm start”以應用這些更改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367774.html
上一篇:如何使邊框位于文本后面?像這樣:
