我正在使用node.js restify来构建REST API服务器。
我已将REST基本身份验证添加到REST API。但是,我只想要一些选定的API进行身份验证。目前,所有REST API都必须经过身份验证。
启用HTTP基本身份验证的代码;
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()
的身份验证。
答案 0 :(得分: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