Nodejs-证书链中的错误自签名证书

我面临着客户端 https 请求的问题。

一个片段可以是这样的:

var fs = require('fs');
var https = require('https');


var options = {
hostname: 'someHostName.com',
port: 443,
path: '/path',
method: 'GET',
key: fs.readFileSync('key.key'),
cert: fs.readFileSync('certificate.crt')
}


var requestGet = https.request(options, function(res){
console.log('resObj', res);
}

我得到的是错误: 证书链中的自签名证书。

当我使用 Postman 时,我可以导入客户端证书和密钥,并毫无问题地使用它。有什么解决办法吗?我还想了解一下邮递员是如何处理证书和工作的。

260241 次浏览

Option 1: Disable the warning (useful for dev)

From your question I'm guessing you are doing this in development as you are using a self signed certificate for SSL communication.

If that's the case, add as an environment variable wherever you are running node

export NODE_TLS_REJECT_UNAUTHORIZED='0'
node app.js

or running node directly with

NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js

This instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority)

If you don't want to set an environment variable or need to do this for multiple applications npm has a strict-ssl config you set to false

npm config set strict-ssl=false

Option 2: Load in CA cert, like postman (useful for testing with TLS)

If you have a CA cert already like the poster @kDoyle mentioned then you can configure in each request (thanks @nic ferrier).

 let opts = {
method: 'GET',
hostname: "localhost",
port: listener.address().port,
path: '/',
ca: fs.readFileSync("cacert.pem")
};


https.request(opts, (response) => { }).end();

Option 3: Use a proper SSL Cert from a trusted source (useful for production)

letsencrypt.org is free, easy to set up and the keys can be automatically rotated. https://letsencrypt.org/docs/

You can write command npm config set strict-ssl false

Turning off verification is quite a dangerous thing to do. Much better to verify the certificate.

You can pull the Certificate Authority certificate into the request with the ca key of the options object, like this:

let opts = {
method: 'GET',
hostname: "localhost",
port: listener.address().port,
path: '/',
ca: await fs.promises.readFile("cacert.pem")
};


https.request(opts, (response) => { }).end();

I put a whole demo together of this so you can see how to construct SSL tests.

It's here.

you just add at the start of your code this line:

process.env.NODE_TLS_REJECT_UNAUTHORIZED='0'

And everything solved, but in any case it is not recommendable, I am investigating the solution of https://letsencrypt.org/

You can fix this issue using NODE_TLS_REJECT_UNAUTHORIZED=0 in the terminal or inserting the following line within the JS file.

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

Beware that this a hack and it should not be used in production.

If you are using windows then run the following command in the command prompt:

set NODE_TLS_REJECT_UNAUTHORIZED=0

After that, npm install <my-package> will work.

For what it's worth, after spending a day and a half trying to track this one down it turned out the error was caused by a setting on my company's firewall that IT had to disable. Nothing anywhere on the internet did anything to fix this.

for Nodemailer:

adding

tls: {
rejectUnauthorized: false
}

solved my problem.

Overall code looks liek this:

nodemailer.createTransport({
host: process.env.MAIL_SERVER,
secure: false,
port: 587,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD
},
tls: {
rejectUnauthorized: false
}
}

The node application needs to have the CA certificate added to the existing CA (Mozilla) certificates.

We start node using a service, and add the environment variable, NODE_EXTRA_CA_CERTS

[Service]
Restart=always
User=<...>
Group=<...>
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
Environment=NODE_EXTRA_CA_CERTS=/<...>/.ssl/extra_certs.pem
WorkingDirectory=/<...>


ExecStart=/usr/bin/node -r dotenv/config /<.....>/server.js dotenv_config_path=/<....>/.env

This way we can use the same application to call services using popular CAs or our own self signed certs, and we don't have to turn off SSL checking.

In linux there is an easy way to get the certificate, use this post: Use self signed certificate with cURL?

You create your certificate using:

$ echo quit | openssl s_client -showcerts -servername server -connect server:443 > cacert.pem

then copy that .pem file as the extra_cert.pem. You can only have one pem file, but you can append multiple pem files into one file.

I hope this helps someone, it took me a while to find the different parts to make this work.

Do:

Better use this if running a node script for standalone purpose,

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

Don't:

instead of changing all default request process.

npm config set strict-ssl=false

i.e., don't alter your node config, else it will apply to all your requests, by making it default config. So just use it where necessary.

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; Even though its not worked ...

Not Able to Install Cypress:

S C:\Cypress> export NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again. At line:1 char:1

  • export NODE_TLS_REJECT_UNAUTHORIZED='0' node app.js
  •   + CategoryInfo          : ObjectNotFound: (export:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException