在某些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
- RESTful API是否会返回不同的状态码或令牌过期和未经授权的错误消息?
- Google OAuth2:缺less必需的参数:grant_type
- 使用快递服务静态文件时,不能使用基本身份validation
- 错误:401(未授权),Passport身份validation在节点中
- 由于连接不再使用parseCookie方法,我们如何使用express来获取会话数据?
- 在NodeJS后端使用JWT和Active Directoryauthentication
- 是否有一个node.js框架提供像spring-security一样的授权和authentication?
- 在Heroku上制作一个NodeJs应用程序
- 将Node.JS代码片段转换为Javascript(Google Apps脚本)