【问题标题】:Self-signed certificates in ElectronElectron 中的自签名证书
【发布时间】:2021-01-03 11:56:32
【问题描述】:

我正在尝试设置一个在自定义本地域上使用 API 的项目(本地 DNS 服务器将自定义 tld 重定向到 localhost)。在我的计算机上,我有一个带有 mkcert 证书的 nginx 反向代理,该证书已在 Firefox、Chrome 和 Curl 中加载并运行(证书已安装并运行)。我正在运行 archlinux,如果这相关的话。

当我尝试使用电子应用程序时,我收到消息“证书链中的自签名证书”。

有什么办法可以解决这个问题吗?我已经尝试使用 nodejs 的 env var 禁用 ssl 验证并使用 syswidecas npm 包但没有运气。

【问题讨论】:

    标签: node.js ssl electron certificate self-signed


    【解决方案1】:

    更好的方法是设置自定义证书验证过程。您可以通过调用以下函数来做到这一点:

    const { BrowserWindow } = require('electron')
    const win = new BrowserWindow()
    
    win.webContents.session.setCertificateVerifyProc((request, callback) => {
      const { hostname } = request
      if (hostname === 'example.com') { //this is blind trust, however you should use the certificate, valdiatedcertifcate, verificationresult as your verification point to call callback
        callback(0); //this means trust this domain
      } else {
        callback(-3); //use chromium's verification result
      }
    })
    

    有关更多详细信息,请阅读以下内容: https://www.electronjs.org/docs/api/session#sessetcertificateverifyprocproc

    【讨论】:

      【解决方案2】:

      这不是 Node.js 的问题,而是嵌入在 Electron 中的 Chromium 的问题。要真正信任 Chromium 拒绝的每个证书,您可以使用Electron documentation 中的以下示例中的代码:

      // in your main process, having Electron's `app` imported
      app.on ("certificate-error", (event, webContents, url, error, cert, callback) => {
          // Do some verification based on the URL to not allow potentially malicious certs:
          if (url.startsWith ("https://yourdomain.tld")) {
              // Hint: For more security, you may actually perform some checks against
              // the passed certificate (parameter "cert") right here
              
              event.preventDefault (); // Stop Chromium from rejecting the certificate
              callback (true);         // Trust this certificate
          } else callback (false);     // Let Chromium do its thing
      });
      

      【讨论】:

      • 我已经在某处看到过这段代码,不幸的是,根据调试器,它永远不会被触发并导致同样的错误。即使没有域检查...
      • 嗯?这很奇怪……你也可以尝试在BrowserWindowWebContents上使用这个事件;不要引用我的话,但我相信它应该在那里工作。参见docs,但用法其实是一样的(只需将appwindow.webContents 互换)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多