RequestJS - SSL连接已授权,但getPeerCertificate()返回null

kognpnkq  于 4个月前  发布在  其他
关注(0)|答案(3)|浏览(76)

我在node v4.1.2上使用node包RequestJS v2.65.0
我正在尝试从某些站点(例如GitHub.com)读取SSL证书。**这以前在节点0.12上有效。但是,在节点4.2.1上,getPeerCertificate()返回null
举例来说:

request({
  url: 'https://github.com'
}, function (err, res, body) {
  console.log('err:', err)
  console.log('peerCertificate:',res.req.connection.getPeerCertificate());
  console.log('authorized:',res.req.connection.authorized);
  console.log('authorizationError:',res.req.connection.authorizationError);
});

字符串
将打印出

err: null
peerCertificate: null
authorized: true
authorizationError: null


即建立了安全连接但证书为空。
从我的(基本)理解,如果连接是授权的,应该有一个对等证书。
我尝试了很多SSL站点,结果都是一样的。是request中的选项,Node 4的bug,还是我对Node中SSL/TLS的工作原理有误解?

4ngedf3f

4ngedf3f1#

我认为你的问题是因为getPeerCertificate()只会在连接处于connected状态时输出任何东西,但是当你收到你的响应时,可能已经太晚了。
如果你想让getPeerCertificate输出,你应该在TLS级别独立地这样做:

const socket = require('tls').connect(443, "github.com", () => {
  console.log('client connected',
    socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});

字符串

重要提示!不要将协议放在URL中,而是使用require('url').parse(yourURL).hostname作为目标。

更多信息和示例请访问:https://nodejs.org/api/tls.html#tls_tls_connect_port_host_options_callback

huus2vyu

huus2vyu2#

@nembleton关于为什么会发生这种情况是正确的。在https://github.com/request/request/issues/1867上有一个问题
你可以坚持使用Request并使用它的流API,而不是直接使用原始TLS套接字。如果你正在利用其他Request功能,这将使底层连接更加复杂(例如通过HTTPS代理),这种方法特别有用。
原始问题中的代码片段变为:

request({
  url: 'https://github.com'
})
.on('error', function(err) {
    console.log('err:', err);
})
.on('response', function (res) {
  console.log('peerCertificate:',res.socket.getPeerCertificate());
  console.log('authorized:',res.socket.authorized);
  console.log('authorizationError:',res.socket.authorizationError);
});

字符串
(为了简洁/直接,我使用了res.socket而不是res.req.connection,但两者都可以工作。

huus2vyu

huus2vyu3#

我在构建一个检查SSL证书过期的API时遇到了这个问题。
下面是代码为我工作。

import https from 'node:https';

const checkSsl = (hostname) => new Promise((resolve, reject) => {
  const req = https.request({
    hostname,
    agent: new https.Agent({ maxCachedSessions: 0 }), // Disable session caching
  }, (res) => {
    const certificate = res.socket.getPeerCertificate();
    resolve(certificate);
  });

  req.on('error', (e) => {
    reject(e);
  });
  req.end();
});

字符串
getPeerCertificate()会在会话建立并缓存时返回null。但非缓存代理会保证详细的结果。

相关问题