Self-signed certificates in Electron

Viewed 3362

I'm trying to setup a project which uses APIs on a custom local domain (Local DNS server redirecting a custom tld to localhost). On my computer I'm having a nginx reverse-proxy with a mkcert certificate that is loaded and working in Firefox, Chrome and Curl (Certificate is installed and working). I'm running archlinux, if this is related.

When I try to use the electron app, I'm getting the message "self signed certificate in certificate chain".

Any way to fix this issue ? I've already tried to disable ssl verification with the nodejs' env var and used the syswidecas npm package but no luck.

2 Answers

This is not a problem with Node.js, it's a problem with the Chromium embedded in Electron. To actually trust every certificate Chromium rejects, you can use code along the lines of the following example from the 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
});

A better way is to set a custom certificate verification proc. You can do this by calling the following function:

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
  }
})

For more details read this: https://www.electronjs.org/docs/api/session#sessetcertificateverifyprocproc

Related