我试图从jira服务器下载一个文件使用URL,但我得到一个错误。 如何在代码中包含证书进行验证?

错误:

Error: unable to verify the first certificate in nodejs

at Error (native)
    at TLSSocket.<anonymous> (_tls_wrap.js:929:36)
   
  at TLSSocket.emit (events.js:104:17)

at TLSSocket._finishInit (_tls_wrap.js:460:8)

我的Nodejs代码:

var https = require("https");
var fs = require('fs');
var options = {
    host: 'jira.example.com',
    path: '/secure/attachment/206906/update.xlsx'
};

https.get(options, function (http_res) {
    
    var data = "";

  
    http_res.on("data", function (chunk) {
       
        data += chunk;
    });

   
    http_res.on("end", function () {
      
        var file = fs.createWriteStream("file.xlsx");
        data.pipe(file);
      
    });
});

当前回答

GoDaddy SSL CCertificate

我在尝试使用GoDaddy证书连接到我们的后端API服务器时遇到过这种情况,下面是我用来解决问题的代码。

var rootCas = require('ssl-root-cas/latest').create();

rootCas
  .addFile(path.join(__dirname, '../config/ssl/gd_bundle-g2-g1.crt'))
  ;

// will work with all https requests will all libraries (i.e. request.js)
require('https').globalAgent.options.ca = rootCas;

PS:

使用捆绑的证书,不要忘记安装npm install ssl-root-cas库

其他回答

我正在使用nodemailer npm模块。下面的代码解决了这个问题

     tls: {
     // do not fail on invalid certs
     rejectUnauthorized: false
     }

我们已经提供了有效的根。pem和Intermediate。返回请求对象的agentOptions属性中的pem证书

ex:

   agentOptions: {
        ca: [
            fs.readFileSync("./ROOT.pem"),
            fs.readFileSync("./Intermediate.pem"),
        ],
    },

欲了解更多信息:https://stackoverflow.com/a/72582263/4652706

另一个肮脏的黑客,这将使你所有的请求不安全:

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0

您试图下载的服务器可能配置错误。即使它在您的浏览器中工作,它也可能不包括缓存空客户端验证所需的链中的所有公共证书。

我建议在SSLlabs工具中检查该站点:https://www.ssllabs.com/ssltest/

查找以下错误:

此服务器的证书链不完整。

这:

链问题……不完整

您可以通过如下所示修改请求选项来做到这一点。如果使用自签名证书或缺少中介,将strictSSL设置为false将不会强制请求包验证证书。

var options = {
   host: 'jira.example.com',
   path: '/secure/attachment/206906/update.xlsx',
   strictSSL: false
}