NodeJs HTTP代理基本身份验证

时间:2017-05-28 10:35:18

标签: node.js http basic-authentication

我正在尝试实现一个简单的HTTP代理,它只会尝试在目标主机上执行基本身份验证。

到目前为止,我有以下内容:

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);

然而," auth:' real_user:real_password'"似乎没有做任何事情。也试过了:

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

2 个答案:

答案 0 :(得分:1)

您必须生成身份验证标头

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);

答案 1 :(得分:1)

DeprecationWarning:由于安全性和可用性问题,不建议使用Buffer()。请使用

    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);