0

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.

Community
  • 1
  • 1
Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135
  • Consider using [passport user & password authentication](http://passportjs.org/guide/username-password/) – drorw May 10 '14 at 19:04

1 Answers1

0

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();
};
Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135