Reputation: 300
I'm having some trouble with basic auth in Node.
Here's how I can do it via cURL as child process:
var auth = 'Basic ' + new Buffer(username + ":" + password).toString('base64');
var url = 'https://' + hostname + path;
var curlstr = "curl #{url} -H 'Authorization: #{auth}'"
.replace('#{url}', url)
.replace('#{auth}', auth);
require('child_process').exec(curlstr, function (err, stdout, stderr){
console.log(stdout);
});
But it's returning 403s when I try https.request:
var req = https.request({
hostname: hostname,
path: path,
headers: {'Authorization': auth}
}, function (res){
console.log(res.statusCode);
});
req.end();
And I get the same results with request:
request({
method: 'GET',
url: url,
auth: {
username: username,
password: password
}
}, function (err,res,body){
console.log(res.statusCode);
});
Any ideas what I'm doing wrong here?
Upvotes: 2
Views: 1446
Reputation: 300
The server was expecting a User-Agent.
request({
method: 'GET',
url: url,
headers: {'User-Agent': 'curl'},
auth: {
username: username,
password: password
}
}, function (err,res,body){
console.log(body);
});
Does the job.
Upvotes: 1
Reputation: 3669
Since it's https, could try adding port
option with value 443
.
var req = https.request({
hostname: hostname,
port: 443,
path: path,
headers: {'Authorization': auth}
}, function (res){
console.log(res.statusCode);
});
req.end();
Or with auth
option instead of header
.
Ref: http://nodejs.org/api/http.html#http_http_request_options_callback
var req = https.request({
hostname: hostname,
port: 443,
path: path,
auth: username + ':' + password
}, function (res){
console.log(res.statusCode);
});
req.end();
Upvotes: 1