guagay_wk
guagay_wk

Reputation: 28050

Selectively enable HTTP basic authentication on some REST APIs

I am using node.js restify to build a REST API server.

I have added HTTP Basic authentication to the REST APIs. However, I only want some selected APIs to have authentication. Currently, all the REST APIs have to be authenticated.

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

Here are some of the APIs I have;

var api_get_XXX = function (app) {
    function respond(req, res, next) {
    //action
    }; 
    // Routes
    app.get('/XXX', respond);
} 

var api_get_YYY = function (app) {
    function respond(req, res, next) {
    //action
    }; 
    // Routes
    app.get('/YYY', respond);
} 

var api_get_ZZZ = function (app) {
    function respond(req, res, next) {
    //action
    }; 
    // Routes
    app.get('/ZZZ', respond);
} 

api_get_XXX(server);
api_get_YYY(server);
api_get_ZZZ(server);

I would like to enable authentication for api_get_XXX(), api_get_YYY() but disable authentication for api_get_ZZZ().

Upvotes: 2

Views: 204

Answers (1)

Shanoor
Shanoor

Reputation: 13682

You could maintain an array/object containing the exceptions:

function verifyAuthorizedUser(req, res, next) {
    // list your public paths here, you should store this in global scope
    var publicPaths = {
        '/ZZZ': 1
    };

    // check them here and skip authentication when it's public
    if (publicPaths[req.path()]) {
        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();
}

Or you can use an existing middleware for authentication: https://github.com/amrav/restify-jwt

Upvotes: 1

Related Questions