我试图从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);
      
    });
});

当前回答

我遇到过非常罕见的情况,但希望它能帮助到某人:做一个代理服务,代理请求到另一个服务。而且每个请求的错误都是“无法验证第一个证书”,即使我添加了所有预期的证书。

原因很简单-我不小心重新发送也“主机”头。 只是要确保你没有显式地发送“host”头。

其他回答

对于无法验证nodejs中的第一个证书,需要拒绝未经授权的证书

 request({method: "GET", 
        "rejectUnauthorized": false, 
        "url": url,
        "headers" : {"Content-Type": "application/json",
        function(err,data,body) {
    }).pipe(
       fs.createWriteStream('file.html'));

这实际上为我解决了这个问题,从https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

解决这个问题的另一种方法是使用下面的模块。

node_extra_ca_certs_mozilla_bundle

该模块无需任何代码修改,即可生成包含Mozilla信任的所有根证书和中间证书的PEM文件。您可以使用以下环境变量(适用于Nodejs v7.3+),

NODE_EXTRA_CA_CERTS

生成与上述环境变量一起使用的PEM文件。你可以使用以下方法安装模块:

npm install --save node_extra_ca_certs_mozilla_bundle

然后使用环境变量启动节点脚本。

NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js

使用生成的PEM文件的其他方法如下:

https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle

注:我是上述模块的作者。

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

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

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

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