Home > OS >  How to obtain the username and password from the URI with NodeJS HTTP2 module?
How to obtain the username and password from the URI with NodeJS HTTP2 module?

Time:09-03

When receiving a request with the form https://username:[email protected] using nodejs http2 module, how can I access the username and password?

Specifically, when responding to an on('stream') event?

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.

CodePudding user response:

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.

If this header is empty: Do you have any reverse proxy between your client and node?

  • Related