23

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
jtlindsey
  • 4,346
  • 4
  • 45
  • 73

5 Answers5

57

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

Pang
  • 9,564
  • 146
  • 81
  • 122
Peter Stegnar
  • 12,615
  • 12
  • 62
  • 80
  • 4
    This is only valid if the request comes from the `renderer` process, isn't it? Is there a way to intercept requests from `request` or `axios` on the `main` process? – Marco Ancona Aug 24 '18 at 16:16
  • Recommend to add a regex check for the specific URL for extra security, e.g. `if (/xxx\.xxx\.xxx\.xxx/g.test(url)) { ... }` – Roy Shilkrot Nov 22 '19 at 18:14
9

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

Vadim Macagon
  • 14,463
  • 2
  • 52
  • 45
6

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

if (process.env.NODE_ENV === 'DEV') {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
}
Joe
  • 384
  • 3
  • 13
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.

XYZ
  • 331
  • 3
  • 4
3

In the app entry file, do:

const { app } = require('electron')

app.commandLine.appendSwitch('ignore-certificate-errors')
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90