在某些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
- 在对Google表单进行多次调用时,API身份validation不适用于第二次调用:请求的身份validation范围不足
- 在Nodejs中使用Google API进行服务validation
- 我们如何在node.js中使用Firebase Auth创build用户?
- 如何在使用mocha / chai进行unit testing时覆盖护照authentication?
- 如何在Express.js中设置authentication中间件
- OAuth2服务器:无效或缺lessgrant_type参数
- 我如何使用node.js和PHP来请求谷歌浏览器中的客户端js的大查询authentication
- 由于连接不再使用parseCookie方法,我们如何使用express来获取会话数据?
- 设置第三方node.jsauthentication服务器