当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - How to request authentication in NodeJS

问题描述:

This question shows how to parse authorization headers, but how do I request the client to send the authorization? I think I have to set a header, but how to do that in node, I'm not sure. Of course, if it doesn't, I just send a 401, but Chrome doesn't know to ask me for a username and password (probably with good reason). Here's what I have so far.

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

Also, if it doesn't set the header, I just want to return the header portion of the 401 to save processing and bandwidth.

网友答案:

OK, here's what I came up with.

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();
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: