使用自签名证书时无法从 Electron 连接到网络套接字



我有一个Electron应用程序,它试图通过Web套接字连接到设备。连接是加密的(即 wss),但 SSL 证书是自签名的,因此不受信任。

在Chrome内部连接是可以的,它可以工作。然而,在Electron内部,我遇到了问题。在没有将任何certificate-error处理程序放在BrowserWindow或应用程序上的情况下,我在控制台输出中收到以下错误:

WebSocket 连接到"wss://some_ip:50443/"失败:连接建立时出错:net::ERR_CERT_AUTHORITY_INVALID

然后不久之后:

  • 用户正在关闭 WAMP 连接...。遥 不可 及

在我的代码中,为了建立连接,我运行以下命令。


const connection = new autobahn.Connection({
realm: 'some_realm',
url: 'wss://some_ip:50443'
});
connection.onopen = (session, details) => {
console.log('* User is opening WAMP connection....', session, details);
};
connection.onclose = (reason, details) => {
console.log('* User is closing WAMP connection....', reason, details);
return true;
};
connection.open();
// alternatively, this also displays the same error
const socket = new WebSocket(`wss://some_ip:50443`);
socket.onopen = function (event) {
console.log(event);
};
socket.onclose = function (event) {
console.log(event);
};

注意:Autobahn 是一个 Websocket 库,用于使用 WAMP 协议连接到某种套接字服务器。(就我而言,设备)底层协议是wss。在上面的代码下面,正在调用本机 JSnew WebSocket()。换句话说:

正如我提到的,我已经在浏览器窗口中测试了此代码并且它可以工作。我还构建了一个较小的应用程序来尝试隔离问题。还是没有运气。

我尝试将以下代码添加到我的main.js进程脚本中:

app.commandLine.appendSwitch('ignore-certificate-errors');

win.webContents.on('certificate-error', (event, 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);
});

app.on('certificate-error', (event, webContents, link, 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);
});

这会将错误更改为:

WebSocket 与"wss://some_ip:50443/"的连接失败:WebSocket 打开握手被取消

我的理解是,上面的"证书错误"处理程序应该转义任何SSL证书错误并允许应用程序继续。然而,他们不是。

我还尝试将以下内容添加到main.js

win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = '1';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

使用Election,如何正确处理来自不受信任的颁发机构的证书?即自签名证书。

任何帮助将不胜感激。

我遇到了同样的问题,我添加的只是你的行:

app.commandLine.appendSwitch('ignore-certificate-errors');

我使用 socket.io,但我认为这是相同的原则。 但是,我确实连接到https协议,而不是直接连接到wss。

这是我的连接在页面上的样子:

socket = io.connect(
'https://yoursocketserver:yourport', {
'socketpath',
secure: false,
transports: ['websocket']
});

这似乎已经成功了。 感谢您的帮助:)我希望这个答案也能帮助你。

最新更新