问题描述
我正在尝试建立一个在自定义本地域(本地DNS服务器将自定义tld重定向到本地主机)上使用API的项目。在我的计算机上,我有一个带有mkcert证书的Nginx反向代理,该证书已在Firefox,Chrome和Curl中安装并正常工作(证书已安装并正常工作)。如果相关,我正在运行archlinux。
当我尝试使用电子应用程序时,我收到消息“证书链中的自签名证书”。
任何解决此问题的方法吗?我已经尝试使用nodejs的env var禁用ssl验证,并使用了syswidecas npm软件包,但是没有运气。
解决方法
这不是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
});
,
更好的方法是设置自定义证书验证过程。您可以通过调用以下函数来执行此操作:
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