简体   繁体   English

如何使用 NodeJS HTTP2 模块从 URI 中获取用户名和密码?

[英]How to obtain the username and password from the URI with NodeJS HTTP2 module?

When receiving a request with the form https://username:password@example.com using nodejs http2 module , how can I access the username and password?使用 nodejs http2 模块收到格式为 https://username:password@example.com 的请求时,如何访问用户名和密码?

Specifically, when responding to an on('stream') event?具体来说,在响应on('stream')事件时?

The provided headers object did not contain any pseudo headers with the user-info, and I could not find a mention for it in the docs.提供的标头 object 不包含任何带有用户信息的伪标头,我在文档中找不到它的提及。

It should be pretty straight forward:它应该很简单:

// server.js
const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream, headers) => {
  console.log(headers['authorization']);
  stream.respond({
    ':status': 200,
  });
  stream.write('Hello World!');
  stream.end();
});

server.listen(8080);

Test it with:测试它:

curl --http2-prior-knowledge http://user:pass@localhost:8080

or use this snippet as node client:或将此片段用作节点客户端:

// client.js
const http2 = require('http2')

const session = http2.connect('http://localhost:8080')

const req = session.request({
  ':path': '/',
  authorization: 'Basic dXNlcjpwYXNz',
})
req.end()

req.setEncoding('utf8')
let data = ''
req.on('data', (chunk) => {
  data += chunk
})

req.on('end', () => {
  console.log(data)
  session.close()
})

You then have to split headers['authorization'] and base64 decode the second part.然后,您必须拆分headers['authorization']和 base64 解码第二部分。

If this header is empty: Do you have any reverse proxy between your client and node?如果此 header 为空:您的客户端和节点之间是否有任何反向代理?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM