我的node.js https客户端总是工作,不pipe证书的有效性

该testing程序连接到https服务器并获取一些内容。 我在浏览器中检查了我的服务器并使用了curl,证书正常工作。 如果我运行curl从服务器获取数据,它会正确地抱怨证书未知,除非我使用–cacert传入或使用-kclosures安全性。

所以我现在面临的问题是,尽pipe我认为我的客户应该做证书authentication,而且我正在告诉它公共证书在哪里,它总是有效的。 如果我删除ca:选项,所以它不知道服务器的证书是什么,那么它默默地工作。 我想赶上authentication错误,但我似乎无法这样做。

var https = require('https'); var fs = require('fs'); function main() { var data = ''; var get = https.get({ path: '/', host: 'localhost', port: 8000, agent: false, ca: [ fs.readFileSync('https_simple/cacert.pem') ] }, function(x) { x.setEncoding('utf8'); x.on('data', function(c) {data += c}); x.on('error', function(e) { throw e; }); x.on('end', function() { console.log('Hai!. Here is the response:'); console.log(data); }); }); get.on('error', function(e) {throw e}); get.end(); } main(); 

为了使这个工作,我需要升级到V0.7.8(虽然任何V0.7应该罚款)的rejectUnauthorizedfunction已被添加到https.get

这些选项的组合是必要的:

 agent: false, // or you can supply your own agent, but if you don't you must set to false rejectUnauthorized: true, ca: [ fs.readFileSync('https_simple/cacert.pem') ] 

现在,如果authentication失败,您将收到“错误”事件,请求将不会继续。

有关制作自己的代理的详细信息,请参阅https.request 文档

错误修正是在这个改变中提交的: https : //github.com/joyent/node/commit/f8c335d0

根据https.request的文档 , https.requesthttps.requestca选项是来自tls.connect的选项。 tls.connect模块函数选项的文档状态如下:

ca :可信证书的string或缓冲区数组。 如果省略,将使用几个众所周知的“根”CA,例如VeriSign。 这些用于授权连接。

挖掘node.js源代码,可以在这里find使用的根证书: https : //github.com/joyent/node/blob/master/src/node_root_certs.h

因此,简而言之,没有授权证书作为https.get的选项提供, tls模块将尝试使用根证书列表进行身份validation。

我使用请求模块在npm中执行此操作。 它是这样的:

 var cacert = ... // in npm, this is a config setting var request = require("request") request.get({ url: "https://...", ca: cacert, strictSSL: true }) .on("response", function (resp) { ... }) .on("error", function (er) { ... }) 

如果ssl无效,则会引发错误事件。

在V 0.6.15中,您需要明确检查证书validation是否通过或失败。

 if (x.connection.authorized === false) { console.log('SSL Authentication failed'); } else if (x.connection.authorized === true) { console.log('SSL Authentication succeeded'); }