【发布时间】: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
我有一个电子应用程序,它与我在https://XXX.XX.XX.XXX:port 拥有的服务器同步,该服务器具有自签名证书。如何从我的电子应用程序中信任该证书?
现在我得到:
Failed to load resource: net::ERR_INSECURE_RESPONSE
【问题讨论】:
标签: ssl https electron self-signed
您需要将以下代码放入您的“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 进程上拦截来自request 或axios 的请求?
if (/xxx\.xxx\.xxx\.xxx/g.test(url)) { ... }
订阅app 模块发出的certificate-error 事件并在事件处理程序中验证您的自签名证书。
【讨论】:
如果'certificate-error' 事件不起作用,试试这个:
if (process.env.NODE_ENV === 'DEV') {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
}
【讨论】:
certificate-error 方法不起作用。 env 方法做到了。
看来您也可以通过 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() 了解更多详情。
【讨论】:
在应用入口文件中,执行:
const { app } = require('electron')
app.commandLine.appendSwitch('ignore-certificate-errors')
【讨论】: