jtlindsey
jtlindsey

Reputation: 4863

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

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

Upvotes: 26

Views: 37688

Answers (5)

Wenfang Du
Wenfang Du

Reputation: 11347

In the app entry file, do:

const { app } = require('electron')

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

Upvotes: 4

XYZ
XYZ

Reputation: 391

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.

Upvotes: 4

Peter Stegnar
Peter Stegnar

Reputation: 12925

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

Upvotes: 61

Joe
Joe

Reputation: 404

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

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

Upvotes: 6

Vadim Macagon
Vadim Macagon

Reputation: 14847

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

Upvotes: 9

Related Questions