https请求基本身份验证node.js

kuarbcqp  于 2022-11-29  发布在  Node.js
关注(0)|答案(5)|浏览(277)

我真的越来越疯狂地在网络和stackoverflow上寻找这个。其他关于这个主题的帖子谈论的是http请求,而不是https.com。
我正在用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/

6qftjkof

6qftjkof1#

您没有正确设置http auth选项(即authorization应该改为auth)。

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

kjthegm62#

http/https应该不会对验证造成影响。您的user/pass很可能需要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

p4tfgftt

p4tfgftt3#

不要使用npm包request,因为它已过时,请改用节点本机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()
a64a0gku

a64a0gku4#

有了更新的版本,我可以用基本的身份验证进行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');   
    }

 })
ffvjumwh

ffvjumwh5#

使用Node.js的URL module构建URL对象。如果使用自签名证书调用服务器,则需要httpsAgent模块。

const https = require('https');
const httpsAgent = new https.Agent({
      rejectUnauthorized: false,
});
// Allow SELF_SIGNED_CERT, aka set rejectUnauthorized: false
let options = {
    agent: httpsAgent
}
let address = "10.10.10.1";
let path = "/api/v1/foo";
let url = new URL(`https://${address}${path}`);
url.username = "joe";
url.password = "password123";
url.agent = httpsAgent

let apiCall = new Promise(function (resolve, reject) {
    var data = '';
    https.get(url, options, res => {
        res.on('data', function (chunk){ data += chunk }) 
        res.on('end', function () {
           resolve(data);
        })
    }).on('error', function (e) {
      reject(e);
    });
});

try {
    let result = await apiCall;
} catch (e) {
    console.error(e);
} finally {
    console.log('We do cleanup here');
}

相关问题