【问题标题】:How to request authentication in NodeJS如何在 NodeJS 中请求身份验证
【发布时间】:2014-05-10 15:27:56
【问题描述】:

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);

另外,如果不设置header,我只想返回401的header部分,以节省处理和带宽。

【问题讨论】:

标签: node.js express http-authentication


【解决方案1】:

好的,这就是我想出的。

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();
};

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2017-11-11
    • 2014-02-12
    相关资源
    最近更新 更多