4

我一直在尝试让 Node.JS 使用 SSL 和客户端证书。最初,我曾试图让它与 restify 一起工作(请参阅我的问题here)。当我无法让它发挥作用时,我备份并尝试找到一个示例来说明我正在尝试完成的工作。我试过这个,我收到一个奇怪的错误。

代码如下:

服务器:

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

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

4

2 回答 2

3

把这个服务器放在 nginx 后面怎么样?

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

寻找使用 nginx 的代理示例)。

PS
这两个应用程序可以并且可能驻留在同一台服务器计算机中。

于 2012-10-23T10:51:51.813 回答
2

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

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

于 2016-03-09T16:10:55.703 回答