在某些REST API上select性启用HTTP基本authentication

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

我已经将HTTP基本身份validation添加到REST API。 但是,我只想要一些选定的API进行身份validation。 目前,所有的REST API都必须经过authentication。

启用HTTP基本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); 

这里有一些我有的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()启用身份validation,但是禁用api_get_ZZZ()身份validation。

你可以维护一个包含exception的数组/对象:

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

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