Restify static webserver stops working after enabling HTTP basic authentication

徘徊边缘 提交于 2019-12-12 06:05:31

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34431478/restify-static-webserver-stops-working-after-enabling-http-basic-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!