2017-05-28 240 views
0

我試圖實現一個簡單的HTTP代理,它只會嘗試在目標主機上執行基本身份驗證。NodeJs 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); 

然而, 「身份驗證: 'real_user:real_password'」 似乎並沒有做任何事情。也試過:

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

回答

0

你產生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);