【问题标题】:How do I trust a self signed certificate from an electron app?如何信任来自电子应用程序的自签名证书?
【发布时间】:2016-12-23 12:35:37
【问题描述】:

我有一个电子应用程序,它与我在https://XXX.XX.XX.XXX:port 拥有的服务器同步,该服务器具有自签名证书。如何从我的电子应用程序中信任该证书?

现在我得到:

Failed to load resource: net::ERR_INSECURE_RESPONSE

【问题讨论】:

标签: ssl https electron self-signed


【解决方案1】:

您需要将以下代码放入您的“shell”(核心电子初始化)文件中:

// SSL/TSL: this is the self signed certificate support
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
    // On certificate error we disable default behaviour (stop loading the page)
    // and we then say "it is all fine - true" to the callback
    event.preventDefault();
    callback(true);
});

这将允许不安全(无效)的证书,如自签名证书。

⚠ 请注意,这不是一种安全的方式连接到服务器。

有关更多信息,请查看文档:
https://electron.atom.io/docs/api/app/#event-certificate-error

【讨论】:

  • 这仅在请求来自renderer 进程时才有效,不是吗?有没有办法在main 进程上拦截来自requestaxios 的请求?
  • 建议为特定 URL 添加正则表达式检查以提高安全性,例如if (/xxx\.xxx\.xxx\.xxx/g.test(url)) { ... }
【解决方案2】:

订阅app 模块发出的certificate-error 事件并在事件处理程序中验证您的自签名证书。

【讨论】:

    【解决方案3】:

    如果'certificate-error' 事件不起作用,试试这个:

    if (process.env.NODE_ENV === 'DEV') {
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
    }
    

    【讨论】:

    • 这似乎是 node 最新版本的解决方案(对我来说是 10.13.0)
    • 对我来说也一样。我发现certificate-error 方法不起作用。 env 方法做到了。
    【解决方案4】:

    看来您也可以通过 setCertificateVerifyProc() 在电子启动脚本的 BrowserWindow 端进行配置。至少在 Electron 10.4.4 中,我无法使用上述任何其他方法。

    例如

    var win = new BrowserWindow({
        ...
    });
    
    win.webContents.session.setCertificateVerifyProc((request, callback) => {
        var { hostname, certificate, validatedCertificate, verificationResult, errorCode } = request;
    
        // Calling callback(0) accepts the certificate, calling callback(-2) rejects it.
        if (isNotMyCertificate(certificate)) { callback(-2); return; }
    
        callback(0);
      });
    

    where isNotMyCertificate() 验证证书中的数据是你的。 console.log() 它来发现证书结构。与一揽子允许所有证书相比,它为您提供了对安全性的更多控制。

    参见https://www.electronjs.org/docs/api/session#sessetcertificateverifyprocproc 中的 setCertificateVerifyProc() 了解更多详情。

    【讨论】:

      【解决方案5】:

      在应用入口文件中,执行:

      const { app } = require('electron')
      
      app.commandLine.appendSwitch('ignore-certificate-errors')
      

      【讨论】:

        猜你喜欢
        • 2018-03-20
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-13
        相关资源
        最近更新 更多