NodeJS无法读取ubuntu中的默认CA.

在我们的testing环境中,我们正在使用本公司签署的SSL连接到另一台服务器。 每次build立连接时,nodejs会抛出UNABLE_TO_VERIFY_LEAF_SIGNATURE 。 我已经通过设置rejectUnauthorized:falsefind了解决方法,但在我们的例子中这不适用。

将证书添加到/ etc / ssl / certs中,并使用环境variablesSSL_CERT_DIR进行testing,以使其成为/ etc / ssl anb / etc / ssl / certs ,但没有结果。

另外,在我们的文件的某个地方添加证书并将其添加到每个请求是不可取的。

这是因为节点不使用您的系统的CAconfiguration; 它包括它自己的可接受CA的内置列表 。

如果您希望节点SSL客户端接受自定义CA,则必须在ca选项中传递CA的证书。

 // do something like this when your app starts up: fs.readFile('/path/to/ca.pem', function(err, cert) { if (err) ... else certBuffer = cert; }); // then when you make requests... https.request({ hostname: 'example.com', port: 443, path: '/', method: 'GET', ca: certBuffer }, ...); 

如果你不想依赖于node.js的内build列表,而是使用你的debian / ubuntu的列表:

 var CAs = fs.readFileSync('/etc/ssl/certs/ca-certificates.crt').toString().split(/(?=-----BEGIN CERTIFICATE-----)/); // then when you make requests... https.request({ ..., ca: CAs}, ...); 

您还可以使用NODE_EXTRA_CA_CERTS环境variables以节点v7.3.0开始,以PEM文件格式添加证书path

https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file

这具有不需要任何代码更改的好处,只需更改node进程的环境即可。 希望这可以帮助!

编辑:

另外检查–use-openssl-ca https://nodejs.org/api/cli.html#cli_use_openssl_ca_use_bundled_ca

这就是我最终用来解决我的问题。 我将我的.crt文件复制到/ usr / local / share / ca-certificates,然后运行sudo update-ca-certificates ,然后使用–use-openssl-ca运行节点,现在节点正确地find我的证书。