https请求基本认证node.js

时间:2014-10-23 18:35:47

标签: javascript node.js authentication https

我真的很疯狂通过网络和stackoverflow寻找这个。 关于这个主题的其他帖子谈论http请求,而不是httpS。

我用node.js编写服务器端,我需要向其他网站发出https请求才能登录

如果我在chrome中使用postman工具尝试使用https://user:pass@webstudenti.unica.it/esse3/auth/Logon.do一切正常,我就会登录。

如果我在节点中使用请求库,我就无法登录,并且我得到一个页面,其中包含有关我的获取/发送数据中的错误的自定义错误消息。

也许我错误地设置传递给请求的选项。

var request = require('request');
var cheerio = require('cheerio');
var user =  'xxx';
var pass = 'yyy';
var options = {
    url : 'https://webstudenti.unica.it',
    path : '/esse3/auth/Logon.do',
    method : 'GET',
    port: 443,
    authorization : {
        username: user,
        password: pass
    }
}

request( options, function(err, res, html){
    if(err){
        console.log(err)
        return
    }
    console.log(html)
    var $ = cheerio.load(html)
    var c = $('head title').text();
    console.log(c);
})

http://jsfiddle.net/985bs0sc/1/

4 个答案:

答案 0 :(得分:4)

您未正确设置http auth options(即authorization应改为auth)。它应该看起来像:

var options = {
    url: 'https://webstudenti.unica.it',
    path: '/esse3/auth/Logon.do',
    method: 'GET',
    port: 443,
    auth: {
        user: user,
        pass: pass
    }
}

答案 1 :(得分:3)

http / https应该在身份验证方面没有区别。您的用户/通行证很可能需要进行base64编码。尝试

var user =  new Buffer('xxx').toString('base64');
var pass = new Buffer('yyy').toString('base64');

请参阅:https://security.stackexchange.com/questions/29916/why-does-http-basic-authentication-encode-the-username-and-password-with-base64

答案 2 :(得分:1)

使用更新的版本,我可以使用基本身份验证进行https呼叫。

var request = require('request');
    request.get('https://localhost:15672/api/vhosts', {
        'auth': {
            'user': 'guest',
            'pass': 'guest',
            'sendImmediately': false
        }
     },function(error, response, body){
    if(error){
        console.log(error)
        console.log("failed to get vhosts");
        res.status(500).send('health check failed');
    }
    else{
            res.status(200).send('rabbit mq is running');   
    }

 })

答案 3 :(得分:0)

不要使用 npm 包 request,因为它已被弃用,请改用 Node 原生 https

const https = require('https')

var options = {
   host: 'test.example.com',
   port: 443,
   path: '/api/service/'+servicename,
   // authentication headers
   headers: {
      'Authorization': 'Basic ' + new Buffer(username + ':' + passw).toString('base64')
   }   
};

//this is the call
request = https.get(options, function(res){
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.end()
相关问题