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

kognpnkq  于 2024-01-08  发布在  其他
关注(0)|答案(3)|浏览(284)

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

  1. request({
  2. url: 'https://github.com'
  3. }, function (err, res, body) {
  4. console.log('err:', err)
  5. console.log('peerCertificate:',res.req.connection.getPeerCertificate());
  6. console.log('authorized:',res.req.connection.authorized);
  7. console.log('authorizationError:',res.req.connection.authorizationError);
  8. });

字符串
将打印出

  1. err: null
  2. peerCertificate: null
  3. authorized: true
  4. authorizationError: null


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

4ngedf3f

4ngedf3f1#

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

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

字符串

重要提示!不要将协议放在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代理),这种方法特别有用。
原始问题中的代码片段变为:

  1. request({
  2. url: 'https://github.com'
  3. })
  4. .on('error', function(err) {
  5. console.log('err:', err);
  6. })
  7. .on('response', function (res) {
  8. console.log('peerCertificate:',res.socket.getPeerCertificate());
  9. console.log('authorized:',res.socket.authorized);
  10. console.log('authorizationError:',res.socket.authorizationError);
  11. });

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

展开查看全部
huus2vyu

huus2vyu3#

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

  1. import https from 'node:https';
  2. const checkSsl = (hostname) => new Promise((resolve, reject) => {
  3. const req = https.request({
  4. hostname,
  5. agent: new https.Agent({ maxCachedSessions: 0 }), // Disable session caching
  6. }, (res) => {
  7. const certificate = res.socket.getPeerCertificate();
  8. resolve(certificate);
  9. });
  10. req.on('error', (e) => {
  11. reject(e);
  12. });
  13. req.end();
  14. });

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

展开查看全部

相关问题