How do I trust a self signed certificate from an electron app?

24,276

Solution 1

You need to put the following code into your "shell" (core electron init) file:

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

This would allow insecure (invalid) certificates like self-signed one.

⚠ Please note that this is NOT a secure way of connecting to the server.

For more, check the documentation:
https://electron.atom.io/docs/api/app/#event-certificate-error

Solution 2

Subscribe to the certificate-error event emitted by the app module and verify your self signed cert in the event handler.

Solution 3

Try this if 'certificate-error' event doesn't work:

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

Solution 4

It appears that you can also configure this on the BrowserWindow side of your electron startup script via setCertificateVerifyProc(). I couldn't get any of the other above methods to work, at least in Electron 10.4.4.

e.g.

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() verifies that the data in certificate is yours. console.log() it to discover the certificate structure. It gives you a bit more control over security than blanket allowing all certificates.

See setCertificateVerifyProc() in https://www.electronjs.org/docs/api/session#sessetcertificateverifyprocproc for more details.

Share:
24,276
jtlindsey
Author by

jtlindsey

Hello, My name is Travis. Im on the web at jtlindsey.com

Updated on July 09, 2022

Comments

  • jtlindsey
    jtlindsey almost 2 years

    I have an electron app that syncs with a server I own at a https://XXX.XX.XX.XXX:port that has a self signed certificate. How can I trust that certificate from my electron app?

    Right now I get:

    Failed to load resource: net::ERR_INSECURE_RESPONSE