我如何信任来自电子应用程序的自签名证书?

时间:2016-08-17 01:09:46

标签: ssl https electron self-signed

我有一个电子应用程序,它与我拥有的https://XXX.XX.XX.XXX:port拥有自签名证书的服务器同步。我怎么能相信我的电子应用程序的证书?

现在我得到:

Failed to load resource: net::ERR_INSECURE_RESPONSE

4 个答案:

答案 0 :(得分:19)

您需要将以下代码放入“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);
    });

但是你允许这样的不安全(无效)证书,比如自签名证书。

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

有关详情,请查看文档:{​​{3}}

答案 1 :(得分:7)

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

答案 2 :(得分:0)

如果'certificate-error'事件不起作用,请尝试以下操作:

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

答案 3 :(得分:0)

看来您也可以通过 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() 了解更多详情。