无论证书有效性如何,我的 node.js https 客户端始终有效 [英] My node.js https client always works regardless of certificate validity

查看:37
本文介绍了无论证书有效性如何,我的 node.js https 客户端始终有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个测试程序连接到一个 https 服务器并获取一些内容.我已经在浏览器和 curl 中检查了我的服务器,并且证书工作正常.如果我运行 curl 从服务器获取数据,它会正确地抱怨证书未知,除非我使用 --cacert 传递它或使用 -k 关闭安全性.

This test program connects to an https server and gets some content. I've checked my server in browsers and with curl and the certificate is working correctly. If I run curl to grab data from the server it correctly complains about the certificate being unknown unless I pass it in with --cacert or turn security off with -k.

所以我遇到的问题是,虽然我认为我的客户应该进行证书身份验证并且我告诉它公共证书在哪里,但它总是有效.如果我删除 ca: 选项,因此它不知道来自服务器的证书是什么,那么它会静默工作.我想捕获身份验证错误,但我似乎无法这样做.

So the problem I am having is that although I think my client should be doing certificate authentication and I am telling it where the public certificate is, it just always works. If I remove the ca: option so it has no idea what the certificate is from the server then it silently works. I would like to catch the authentication error but I can't seem to do so.

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 都应该没问题),其中拒绝未授权功能已添加到 https.get

In order to make this work I needed to upgrade to v0.7.8 (although any v0.7 should be fine) where the rejectUnauthorized functionality has been added to 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') ]

现在,如果身份验证失败,您将收到错误"事件,请求将不会继续.

Now if the authentication fails you will get an 'error' event and the request will not go ahead.

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

See the https.request documentation for details on making your own Agent

在此更改中提交了错误修复:https://github.com/joyent/node/commit/f8c335d0

The bug fix was committed in this change: https://github.com/joyent/node/commit/f8c335d0

这篇关于无论证书有效性如何,我的 node.js https 客户端始终有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆