danizgod
danizgod

Reputation: 359

NodeJs HTTP proxy basic auth

I am trying to implement a simple HTTP proxy that will only try to perform basic auth on the target host.

So far I have the following:

var http = require('http');

const my_proxy =  http.createServer(function(request, response) {
    console.log(request.connection.remoteAddress + ": " + request.method + " " + request.url);

    const options = {
            port: 80
            , host: request.headers['host']
            , method: request.method
            , path: request.url
            , headers: request.headers
            , auth : 'real_user:real_password'
            }
        };

    var proxy_request = http.request(options);

    proxy_request.on('response', function (proxy_response) {
        proxy_response.on('data', function(chunk) {
            response.write(chunk, 'binary');
        });
        proxy_response.on('end', function() {
            response.end();
        });
        response.writeHead(proxy_response.statusCode, proxy_response.headers);
    });

    request.on('data', function(chunk) {
        proxy_request.write(chunk, 'binary');
    });

    request.on('end', function() {
        proxy_request.end();
    });
});
my_proxy.listen(8080);

However, "auth : 'real_user:real_password'" doesn't seem to do anything. Also have tried:

...
auth: {
  user: real_user,
  pass: real_pass
}
...

Upvotes: 1

Views: 3594

Answers (2)

Zilvia Smith
Zilvia Smith

Reputation: 601

DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the

    var username = 'Test';
    var password = '123';
    // Deprecated
    // var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

    var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
    // auth is: 'Basic VGVzdDoxMjM='

    var header = {'Host': 'www.example.com', 'Authorization': auth};
    var request = client.request('GET', '/', header);

Upvotes: 1

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7267

You have to generate the auth header

var username = 'Test';
var password = '123';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);

Upvotes: 1

Related Questions