node.jshttpexpresshttp-authentication

Basic HTTP authentication with Node and Express 4


It looks like implementing basic HTTP authentication with Express v3 was trivial:

app.use(express.basicAuth('username', 'password'));

Version 4 (I'm using 4.2) removed the basicAuth middleware, though, so I'm a little stuck. I have the following code, but it doesn't cause the browser to prompt the user for credentials, which is what I'd like (and what I imagine the old method did):

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
        res.end('Invalid credentials');
    } else {
        next();
    }
});

Solution

  • I used the code for the original basicAuth to find the answer:

    app.use(function(req, res, next) {
        var user = auth(req);
    
        if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
            res.statusCode = 401;
            res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
            res.end('Unauthorized');
        } else {
            next();
        }
    });