简体   繁体   中英

Http Digest Authentication fails in node.js

I am trying to do a http get request with Digest authentication. i am posting my code below`

var digestOption    =   {
                                        'host' : hostName,
                                        'port'  : port,
                                        'path'  : path
                                    }
            http.get(digestOption, function(res){
                var challengeParams = parseDigest(res.headers['www-authenticate'])
                var ha1 = crypto.createHash('md5');
                ha1.update([username,challengeParams.realm,password].join(':'));
                console.log('h1 >>> '+ha1);
                var ha2 = crypto.createHash('md5');
                ha2.update(['GET',digestOption.path].join(':'));
                var response = crypto.createHash('md5');
                response.update([ha1,challengeParams.nonce,'1::auth',ha2].join(':'));
                var authRequestParams = {
                  username : username,
                  realm : challengeParams.realm,
                  nonce : challengeParams.nonce,
                  uri : digestOption.path, 
                  qop : challengeParams.qop,
                  response : response,
                  nc : '1',
                  cnonce : '',
                }
                digestOption.headers = { 'Authorization' : renderDigest(authRequestParams) }
                http.get(digestOption, function(res) {
                  res.setEncoding('utf-8')
                  var content = ''
                  res.on('data', function(chunk) {
                    content += chunk
                  }).on('end', function() {
                    console.log(content)
                  })
                });
            });

` However i am getting

400 Bad request error

I have tested connecting from my browser and got the authentication dialog. Hence there is something wrong with my code.

you can use a trick using the URL itself, as specified in RFC 1738. Simply pass the user/pass before the host with an @ sign.

var request = require('request'),
username = "john",
password = "1234",
url = "http://" + username + ":" + password + "@www.example.com";

request({
    url : url
},
function (error, response, body) {
    // Do more stuff with 'body' here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM