Node.JS + HTTPS + Client Cert =问题

时间:2012-10-22 21:13:23

标签: node.js ssl https client certificate

我一直在努力让Node.JS使用SSL和客户端证书。最初,我试图让它与restify一起工作(参见我的问题here)。当我无法实现这一点时,我进行了备份并试图找到一个例子来说明我想要实现的目标。我试过了this one,我收到了一个奇怪的错误。

代码如下:

服务器:

var sys = require("sys");
var fs = require("fs");
var https = require("https");

var options = {
  key: fs.readFileSync("../certs/server.key"),
  cert: fs.readFileSync("../certs/server.crt"),
  ca: fs.readFileSync("../certs/ca.crt"),
  requestCert: true,
  rejectUnauthorized: true
};

https.createServer(options, function (req, res) {
  console.log(req);
  res.writeHead(200);
  sys.puts("request from: " + req.connection.getPeerCertificate().subject.CN);
  res.end("Hello World, " + req.connection.getPeerCertificate().subject.CN + "\n");
}).listen(8080);

sys.puts("server started");

客户端:

var https = require('https');
var fs = require("fs");

var options = {
    host: 'localhost',
    port: 8080,
    path: '/hello',
    method: 'GET',
    key: fs.readFileSync("../certs/user.key"),
    cert: fs.readFileSync("../certs/user.crt"),
    ca: fs.readFileSync("../certs/ca.crt"),
    passphrase: 'thepassphrase'
};

var req = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    res.on('data', function(d) {
        process.stdout.write(d);
    });
});

req.end();

req.on('error', function(e) {
    console.error(e);
});

运行test-client.js会产生以下结果:

{ [Error: socket hang up] code: 'ECONNRESET' }

用curl尝试同样的事情:

curl -k -v --key user.key --cert user.crt:thepassphrase --cacert ca.crt https://localhost:8080/hello

的产率:

* About to connect() to localhost port 8080 (#0)
*   Trying 127.0.0.1... connected
* successfully set certificate verify locations:
*   CAfile: ca.crt
  CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Request CERT (13):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS handshake, CERT verify (15):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* Unknown SSL protocol error in connection to localhost:8080 
* Closing connection #0
curl: (35) Unknown SSL protocol error in connection to localhost:8080

如果我想要额外的步骤来要求客户证书,我该怎么办呢?

2 个答案:

答案 0 :(得分:3)

如何将此服务器放在nginx后面?

这可能听起来很复杂,或者增加了很多开销,但我保证这很简单,而且nginx的SSL处理很简单。

寻找使用nginx代理example)。

P.S
这两个应用程序都可以并且可能驻留在同一台服务器上。

答案 1 :(得分:2)

在服务器选项和客户端选项中添加rejectUnauthorized: false

告诉nodejs接受自签名证书。另请参阅https://github.com/vanjakom/JavaScriptPlayground/pull/3