连接到我的 api 时电子内容安全策略错误

Electron Content Security Policy error when connecting to my api

创建一个简单的模板电子应用程序。我想向我的 api 发出获取请求,但不断被内容安全策略错误阻止,我不知道如何修复它们。

Refused to connect to 'https://api.myapp.com/' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-inline' data:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

index.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>

app.js

 const handleSubmit = async () => {
    const response = await fetch("https://api.myapp.com/books", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });
    return response.json();
  };

我已尝试将 api 地址添加到现有策略,并添加其他策略,但没有任何效果。

在违规消息中,您有一个白名单:拒绝连接到...以下内容安全策略指令:“default-src 'self' 'unsafe-inline'数据:.

但是在元标记中你显示了不同的白名单:default-src 'self' 'unsafe-eval'.

这意味着您至少有 2 个 CSP 在运行。多个 CSP 充当一致的过滤器 - 所有旨在允许的来源都应通过所有过滤器。因此,应用了所有 CSP 中最严格的规则。

找出您在哪里发布第一个 CSP 并将 connect-src https://api.myapp.com 添加到其中。并删除元标记中的 CSP。

很可能是某些软件包通过 HTTP header 发布了他的默认 CSP(how to check), so the Helmet 受到怀疑 - 它发布了自 v4.
以来的默认 CSP 当然你可以直接发布 CSP HTTP header 代码如下:

session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
  callback({ responseHeaders: Object.assign({
    ...details.responseHeaders,
    "Content-Security-Policy": [ "default-src 'self' 'unsafe-inline' data:" ]
    }, details.responseHeaders)});
  });

我找到了这个问题的答案。似乎 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' 以应用这些更改。