Search code examples
javascriptnode.jsauthenticationrestifybasic-authentication

Restify static webserver stops working after enabling HTTP basic authentication


I have a working node.js restify server configured to work as a static webserver. Here is the relevant code;

var server = restify.createServer({
    name: 'myapp',
    version: '1.0.0'
});

var static_webserver = function (app) {
    app.get(/.*/, restify.serveStatic({
        'directory': 'static', //static html files stored in ../static folder
        'default': 'index.html'
    }));
} //var static_server = function (app)

static_webserver(server);

After I enable HTTP Basic authentication to have better security for the other REST APIs, the static webserver stopped working.

This is the code for enabling HTTP Basic authentication.

server.use(restify.authorizationParser());
function verifyAuthorizedUser(req, res, next)
{
    var users;

    users = {
        foo: {
            id: 1,
            password: 'bar'
        }
    };

    if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
        // Respond with { code: 'NotAuthorized', message: '' }
        next(new restify.NotAuthorizedError());
    } else {
        next();
    }

    next();
}//function verifyAuthorizedUser(req, res, next)

server.use(verifyAuthorizedUser);

It seems that after enabling authentication, no web browser was able to visit the static html webpages because authentication is required. How can I disable authentication for the static webserver but enable authentication for the other REST APIs?


Solution

  • If your nodejs is up to date enough to support string.startsWith():

    function verifyAuthorizedUser(req, res, next) {
        var path = req.path();
        // check if the path starts with /static/
        if (path.startsWith('/static/')) {
            return next();
        }
    
        var users;
        users = {
            foo: {
                id: 1,
                password: 'bar'
            }
        };
    
        if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) {
            // Respond with { code: 'NotAuthorized', message: '' }
            next(new restify.NotAuthorizedError());
        } else {
            next();
        }
    
        next();
    }
    

    If you don't have startsWith(), a good old regex will do:

    if (path.match(/\/static\/.*/)) {
        return next();
    }