Node.js NodeJs HTTP代理基本身份验证
我正在尝试实现一个简单的HTTP代理,它将只尝试在目标主机上执行基本身份验证 到目前为止,我有以下几点:Node.js NodeJs HTTP代理基本身份验证,node.js,http,basic-authentication,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); co
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
}
...
您必须生成auth头
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);
弃用警告:由于安全性和可用性问题,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);