【问题标题】:Selectively enable HTTP basic authentication on some REST APIs在某些 REST API 上选择性地启用 HTTP 基本身份验证
【发布时间】:2016-03-29 15:53:48
【问题描述】:

我正在使用 node.js restify 来构建一个 REST API 服务器。

我已将 HTTP 基本身份验证添加到 REST API。但是,我只希望某些选定的 API 具有身份验证功能。目前,所有 REST API 都必须经过身份验证。

启用 HTTP Basic 身份验证的代码;

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

这是我拥有的一些 API;

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

我想启用api_get_XXX()api_get_YYY() 的身份验证,但禁用api_get_ZZZ() 的身份验证。

【问题讨论】:

    标签: javascript node.js rest authentication restify


    【解决方案1】:

    您可以维护一个包含异常的数组/对象:

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

    或者您可以使用现有的中间件进行身份验证:https://github.com/amrav/restify-jwt

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    相关资源
    最近更新 更多