天天看點

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