Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - My node.js https client always works regardless of certificate validity

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.

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This combination of options is needed:

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...