nodejs之https双向认证
nodejs之https双向认证
前言
之前我们总结了https的相关知识,如果不懂可以看我另一篇文章:白话理解https
有关证书生成可以参考:自签证书生成
正文
使用nodejs来实现https双向认证。
服务端
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./certificate/server-key.pem'),
cert: fs.readFileSync('./certificate/server.pem'),
ca: [fs.readFileSync('./certificate/ca.pem')],
// 使用客户端证书验证
requestCert: true,
// 如果没有请求到客户端来自信任CA颁发的证书,拒绝客户端的连接
rejectUnauthorized: true
};
const port = 8081;
https.createServer(options, (req, res) => {
console.log('server connected', res.connection.authorized ? 'authorized' : 'unauthorized');
res.writeHead(200);
res.end('hello world!\n');
}).listen(port, () => {
console.log(`running server https://127.0.0.1:${port}`)
});
客户端
const https = require('https');
const fs = require('fs');
const options = {
hostname: '127.0.0.1',
port: 8081,
path: '/',
method: 'GET',
key: fs.readFileSync('./certificate/client-key.pem'),
cert: fs.readFileSync('./certificate/client.pem'),
ca: [fs.readFileSync('./certificate/ca.pem')],
agent: false,
// 开启双向认证
rejectUnauthorized: true
};
// options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
console.log('client connected', res.connection.authorized ? 'authorized' : 'unauthorized');
console.log('状态码:', res.statusCode);
res.setEncoding('utf-8');
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();