2012-10-22 138 views
3

我一直試圖讓Node.JS使用SSL和客戶端證書。最初,我試圖讓它與restify一起工作(請參閱我的問題here)。當我無法做到這一點時,我支持並試圖找到一個例子來說明我正在努力完成的事情。我試過this one,我收到一個奇怪的錯誤。Node.JS + HTTPS +客戶端證書=問題

代碼如下:

服務器:

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); 
}); 

運行測試client.js產生這樣的:

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

試圖同有點事情第i個捲曲:

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

把這個服務器放在nginx後面怎麼樣?

這聽起來很複雜,或者增加了很多開銷,但我向你保證它非常簡單,並且nginx的SSL處理非常簡單。

尋找用nginx代理example)。

P.S
這兩個應用程序都可以並可能駐留在同一臺服務器上。

+0

這是一個有趣的答案。 nginx能否將有關用戶證書的信息傳遞給最終的目標網址?可能通過向url添加一些參數? – Chris

+1

這實際上將爲我們工作。謝謝。 – Chris

+0

很高興聽到!最後,你是如何通過nginx轉發證書的?我只是好奇 – Poni