Home > Net >  Calling URL with self-signed cert from Node.js: DEPTH_ZERO_SELF_SIGNED_CERT
Calling URL with self-signed cert from Node.js: DEPTH_ZERO_SELF_SIGNED_CERT

Time:09-27

I have a Python app running on localhost with Flask. I created a self-signed certificate for localhost (created a CA for this too) and loaded the localhost.crt certificate and localhost.key as private key in the Flask app:

app = Flask(__name__)
context = ssl.SSLContext()
context.load_cert_chain(certfile='localhost.crt', keyfile='localhost.key', password='my_password')
app.run(host='127.0.0.1', port=5000, ssl_context=context)

After this I imported my CA's pem file into Windows' trust store. If I call the server in Chrome all good.

However I have a Node.js app on the same PC which is using axios. If I call the above Python app from Node.js I get this:

Error: self signed certificate
    at TLSSocket.onConnectSecure (_tls_wrap.js:1514:34)
    at TLSSocket.emit (events.js:375:28)
    at TLSSocket._finishInit (_tls_wrap.js:936:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:708:12) {
  code: 'DEPTH_ZERO_SELF_SIGNED_CERT',

I have spent some time looking for solutions and some posts mentioned this, so I load the CA pem file into the https agent's ca field:

var https = require('https');
https.globalAgent.options.ca = fs.readFileSync(path.join(__dirname, './myCA.pem'));

But this does not work.

I tried to add a new agent to the axios request:

var agent = new https.Agent({
  ca: fs.readFileSync(path.join(__dirname, './myCA.pem'))
});
var config = {
  method: 'get',
  url: 'https://localhost:5000/test',
  headers: { },
  httpsAgent: agent
};
axios(config).then(function (response) {
  console.log(JSON.stringify(response.data));
}).catch(function (error) {
  console.log(error);
});

But I get the same results. Some posts mention that I need to add a CA bundle here instead, but I have only one CA file, how could I create a bundle if that is needed?

During the generation process I got these files created:

localhost.crt
localhost.csr
localhost.ext
localhost.key
myCA.key
myCA.pem
myCA.srl

Note: Using rejectUnauthorized (and similar) is not an option.

CodePudding user response:

Solved after a lot of reading and trying. When creating the myCA.pem cert and the localhost.crt cert I used the same Common Name. After using a different one and specifying the new httpsAgent in axios as mentioned in my question it all worked.

  • Related