Search code examples
node.jssslcertificatessl-certificate

NodeJS 'DEPTH_ZERO_SELF_SIGNED_CERT'


I get the above error when I try to connect to a webserver with a node.js client I am writing at te moment.

But I get an error when I try to connect to the server.

'DEPTH_ZERO_SELF_SIGNED_CERT'

This is the code that sends the request. And turning off the certificate check is not a valid option. I need the connection to be secured.

var options = 
    {
        hostname: baseUri,
        port: 443,
        path: 'oauth',
        method: 'POST',
        requestCert: true,
        ca:fs.readFileSync('Comodo_PositiveSSL_bundle.crt'),
        rejectUnauthorized: true,
        headers: {
            //'User-Agent': USER_AGENT,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': data.length
        }
    };

    var req = http.request(options, (res) => {
      console.log('statusCode: ', res.statusCode);
      console.log('headers: ', res.headers);

      res.on('data', (d) => {
        process.stdout.write(d);
      });
    });

    req.write(data)
    req.end();

    req.on('error', (e) => {
      console.error(e);
    });

If someone can tell me how I can setup the certification correct so no error is generated?


Picture of the cert bundle. As you can see the bundle contains only the root certificates need to verify the certificate the server provides itself.

Cert bundle


Solution

  • The problem is solved by the code below. I have added options.agent = http.Agent(options);and that solved the problem.

    So for everyone who is trying to authenticate to a secure server and gets the error above, this could be your solution. Below I have added the edited code of the above.

    var options = 
            {
                hostname: baseUri,
                port: 443,
                path: 'oauth',
                method: 'POST',
                requestCert: true,
                headers: {
                    //'User-Agent': USER_AGENT,
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': data.length
                }
            };
            options.agent = http.Agent(options);
    
            var req = http.request(options, (res) => {
              console.log('statusCode: ', res.statusCode);
              console.log('headers: ', res.headers);
    
              res.on('data', (d) => {
                process.stdout.write(d);
              });
            });
    
            req.write(data)
            req.end();
    
            req.on('error', (e) => {
              console.error(e);
            });