我需要为我的静态API创建名为“ access”的身份验证功能,并且每次用户希望与服务器进行交互时,我都希望它的外观如下所示:
access(id , token ,function(err){
if(err){
res.send(err)
}else {
res.send('you have all permissions')
}
})
我如何编写此功能以在每个身份验证步骤中使用?
答案 0 :(得分:0)
对于身份验证,您通常会使用一些中间件:
function isAuthenticated(req, res, next) {
// determine here if user is authenticated (and/or authorized)
if (user) {
next(); // user is authorized, call next
} else {
const error = new Error('unauthorized');
error.status = 400;
return next(err);
}
}
app.get('/authenticated/route', isAuthenticated, function(req, res) {
res.send('secret information');
});
我建议使用类似Passport.js的名称。它删除了很多身份验证中间件,尤其是使它易于与Google和Facebook等提供程序集成。
答案 1 :(得分:0)
如果您的所有条目都可以使用,最好使用中间件
function access(req, res, next) {
// verify token
if (isNotVerified) { return next('You are not verified') }
// otherwise do what you want to do
return next()
}
并将其添加到要验证用户的所有路由中,如下所示:
route.get('/api/private/reports', access, function (req, res) {
// do some stuff only when user is verified
})
route.get('/api/sensitive/information', access, function (req, res) {
// do some stuff only when user is verified
})
希望它将对您有帮助!