无法使用节点请求模块进行基本HTTP身份验证

时间:2016-01-26 14:48:21

标签: javascript node.js http mocha basic-authentication

我正在使用mocha测试我的应用程序,我想根据我使用基本HTTP身份验证发送给它的凭据来测试HTTP响应头代码。

在客户端,我像这样对服务器进行了AJAX调用:

  $.ajax({
    type: 'GET',
    url: url,
    beforeSend: function(xhr){
       xhr.setRequestHeader("Authorization", "Basic " +btoa("username:password") );
     },
     success:function(rsp){
          // do whatever I need;
     }
  });

它完美无缺。凭据是错误的,然后网站会以 302

回复

在我的测试文件( mocha )中,我尝试发送相同的请求但由于某种原因它不起作用。

这是我尝试的不同方式:

it('should return 302 because wrong credentials', function(done){
 var auth = "Basic " +new Buffer("username:password").toString('base64');
  var options = {
      url: url,
      headers: {
      "Authorization": auth
      }
   };

   request.get(options, function(err, res, body){
      console.log(res.statusCode);
      assert.equal(302, res.statusCode);
     done();
   });
});

-----------------------

it('should return 302 because wrong credentials', function(done){
    request.get(url,
    {
      'auth': {
         'username':'username', 
         'password':'password'
       }
    }, 
    function(err, res, body) {
       assert.equal(302, res.statusCode);
       done();
    });
 });

但是,无论如何,我得到一个HTTP 200 响应代码。

为什么?我应该怎么处理它?<​​/ p>

Ps:对于那些非常谨慎的人,不要公开使用客户端,因此我允许自己将凭据放入其中。

编辑:更准确地说,您将在下面找到处理请求的服务器代码(NodeJS)

function checkAuth(req, result, next){

  var header = req.headers['authorization'];

  // Ignore the preflight OPTION call
  if(header != undefined){
    var tmp = header.split(/\s+/).pop();
    var credentials = new Buffer(tmp, 'base64').toString();
    var parts = credentials.split(/:/);
    var username = parts[0];
    var password = parts[1];

    bcrypt.compare(username, config.get.username, function(err, res){
      if(res){
        bcrypt.compare(password, config.get.password, function(err, res){
          if(res){
            next();
          } else {
            return result.redirect('/');
          }
        });
      } else {
        return result.redirect('/');
      }
    });
  } else {
    return result.redirect('/');
  }

}

app.get('/server', checkAuth, getData.getMessages);

方法getData.getMessage()返回以下内容:

return result.status(200).json(res);

2 个答案:

答案 0 :(得分:1)

<item name="colorPrimary">xxxx</item>会自动跟踪重定向,因此您需要停用request来阅读followRedirect个回复。

3xx

答案 1 :(得分:0)

对于HTTP Basic身份验证,您还可以使用http-auth模块。

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ...
});

// Creating new HTTP server.
http.createServer(basic, function(req, res) {
    res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);