javascript - 在某些 REST API 上有选择地启用 HTTP 基本身份验证

标签 javascript node.js rest authentication restify

我正在使用 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() 禁用身份验证。

最佳答案

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

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

关于javascript - 在某些 REST API 上有选择地启用 HTTP 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34431847/

相关文章:

javascript - 显示数组中的某些元素

javascript - 如何在CSS之前加载JavaScript

javascript - .split() 在 IE8 中无法正常工作

node.js - 如何在容器内正确运行nodejs?

rest - DockerHub API : List ongoing builds

ios - Objective-C 中用于 XML POST 的 Rest API

javascript - 有没有办法使用 javascript 从普通 <img> 标签获取图像数据?

javascript - 将 python 请求转移到 node.js 请求时遇到问题

node.js - Mongoose 发现没有获取任何结果

java - 如何为具有withdrawAmount方法的银行应用程序创建幂等操作