如何在NodeJS中请求身份验证

时间:2014-05-10 15:27:56

标签: node.js express http-authentication

This question显示了如何解析授权标头,但如何请求客户端发送授权?我想我必须设置一个标题,但是如何在节点中这样做,我不确定。当然,如果没有,我只发送一个401,但Chrome不知道要问我的用户名和密码(可能是有充分理由的)。这是我到目前为止所拥有的。

var authenticate = function(req, res, next){
  var header=req.headers['authorization']||'',        // get the header
      token=header.split(/\s+/).pop()||'',            // and the encoded auth token
      auth=new Buffer(token, 'base64').toString(),    // convert from base64
      parts=auth.split(/:/),                          // split on colon
      username=parts[0],
      password=parts[1];
  if(header ==''){
    res.send(401, 'Invalid username or password');
    next('Incorrect username or password');
  }
  else next();
};
app.use(authenticate);

另外,如果它没有设置标题,我只想返回401的标题部分以节省处理和带宽。

1 个答案:

答案 0 :(得分:0)

好的,这就是我想出来的。

var authenticate = function(req, res, next){
    if(un == undefined && pw == undefined) { next(); return; }
    if(!req.headers['authorization']){
        res.writeHead(401, {'WWW-Authenticate': 'Basic realm="My Test App"', 'Content-Type': 'text/plain'});
        res.end();
        return;
    }
    var header=req.headers['authorization']||'',        // get the header
        token=header.split(/\s+/).pop()||'',            // and the encoded auth token
        auth=new Buffer(token, 'base64').toString(),    // convert from base64
        parts=auth.split(/:/),                          // split on colon
        username=parts[0],
        password=parts[1];
    if(username != un || password != pw){
        res.send(401, 'Invalid username or password');
        next('Incorrect username or password');
    }
    else next();
};
相关问题