连接到我的 api 时出现 Electron 内容安全策略错误

Chr*_*end 18 html node.js content-security-policy webpack electron

创建一个简单的电子应用程序模板。我想对我的 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>
Run Code Online (Sandbox Code Playgroud)

应用程序.js

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

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

Chr*_*end 20

我找到了这个问题的答案。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;
Run Code Online (Sandbox Code Playgroud)

通过在 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"
                }
              ]
            }
          }
        ]
      ]
Run Code Online (Sandbox Code Playgroud)

注意:更改此设置并保存不会更新应用程序中的策略。您需要停止并再次运行“npm start”才能应用这些更改。

  • 为了让我的电子应用程序与本地主机服务器对话,我做了: `"devContentSecurityPolicy": "default-src 'self' 'unsafe-eval' 'unsafe-inline' http://localhost:* ws://localhost:*; ”,` (3认同)

小智 11

如果您使用 forge.config.ts 您可以使用:

plugins: [
    new WebpackPlugin({
      mainConfig,
      devContentSecurityPolicy: "connect-src 'self' * 'unsafe-eval'",
      renderer: {
        config: rendererConfig,
        entryPoints: [
          {
            html: './src/index.html',
            js: './src/index.tsx',
            name: 'main_window',
            preload: {
              js: './src/preload.ts',
            },
          },
        ],
      },
    }),
  ],
};
Run Code Online (Sandbox Code Playgroud)


gra*_*nty 6

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

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

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

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

最有可能的是某个包通过 HTTP 标头发布了他的默认 CSP(如何检查),因此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)});
  });
Run Code Online (Sandbox Code Playgroud)