I have 2 Node.js applications accessible via HTTPS. I'm currently using self-signed certificates for those services. Manual access (via a browser or Postman) to those services work as expected (with the usual security warnings about self-signed certificates, etc.).
But as for now, I cannot have one application communicate with the other via HTTPS. Here's my current code:
// Request parameters and options
const https = require('https');
const postData = JSON.stringify(myPostData);
const options = {
hostname: '...',
port: ...,
path: '...',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
},
rejectUnauthorized: false,
};
let str = '';
const req = https.request(options, (res) => {
// Assembling response data...
res.on('data', chunk => str += chunk );
res.on('end', () => {
console.log('Received:', str);
});
});
// Error handling
req.on('error', (e) => {
console.error(e);
});
// Sending payload and terminating
req.write(postData);
req.end();
Question
This works, but only because I use rejectUnauthorized: false
.
How can I avoid to use this option? I see that I can provide a cert
option (in https.RequestOptions
), but I'm unsure of how to use it. As I created the self-signed certificate, I possess every pieces of it.
My cert file, named selfsigned.crt
, looks like this (and has Unix EOL):
-----BEGIN CERTIFICATE-----
MFoXDTI0MTEyNTE3NTczMFowgYcxCzAJBgNVBAYTAkZSMQ0wCwYDVQQIDARQQUNB
QGNlbmVhdS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCrP3Hy
........... lots of lines ......................................
zI2hWprwsM3PGb0DLCqlotqdoxu59PQRC7aj/yb11HyfyYO9hvFmjGPkmN6T0+r6
VQQGEwJGUjENMAs/Qs7p+B9/+taee8iPWpk=
-----END CERTIFICATE-----
I have tried these solutions:
- indicated the cert string as the
ca
and/orcert
request options (see their description) - I know this is actually taken into account, as if the string is malformed, the error is different (and related to the certificate format) - indicated the path of the cert to the 'NODE_EXTRA_CA_CERTS' environment variable, as suggested by Ashish Modi)
- copied the cert file in the /etc/ssl/certs/ (calling application OS is debian) and launched
update-ca-certificates
All of those solutions change nothing to the outcome:
code: DEPTH_ZERO_SELF_SIGNED_CERT
Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1055:34)
As for now, I still don't have a working solution.
Bonus question! I'm very surprised how messy a simple call can look, all chronologically upside-down it gets with the callbacks. Is there a cleaner way to proceed a HTTPS call? => request-promise
might be an option, as indicated by jfriend00