[英]Selectively enable HTTP basic authentication on some REST APIs
I am using node.js restify to build a REST API server.我正在使用 node.js restify 来构建 REST API 服务器。
I have added HTTP Basic authentication to the REST APIs.我已将 HTTP 基本身份验证添加到 REST API。 However, I only want some selected APIs to have authentication.
但是,我只希望某些选定的 API 进行身份验证。 Currently, all the REST APIs have to be authenticated.
目前,所有 REST API 都必须经过身份验证。
Code for enabling HTTP Basic authentication;启用 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);
Here are some of the APIs I have;以下是我拥有的一些 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);
I would like to enable authentication for api_get_XXX()
, api_get_YYY()
but disable authentication for api_get_ZZZ()
.我想为
api_get_XXX()
、 api_get_YYY()
启用身份验证但禁用api_get_ZZZ()
身份验证。
You could maintain an array/object containing the exceptions:您可以维护一个包含异常的数组/对象:
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();
}
Or you can use an existing middleware for authentication: https://github.com/amrav/restify-jwt或者您可以使用现有的中间件进行身份验证: https : //github.com/amrav/restify-jwt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.