【发布时间】: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