在我的 Node 应用程序中,我有一个可以发出所有请求的admin
,而普通用户则有权仅发出某些请求。
示例:
管理员可以制作:
在 /root、/user、/tools 上发布
简单的用户可以:
在 /users、/tools
上发帖
如果一个简单的用户尝试在 /root
上发出请求,他只会收到错误消息。
我该如何处理这是 Node js?哪个包,如果可能的话,几个例子。
谢谢
最佳答案
一般方法应该是定义一个自定义中间件来验证身份验证
function VerifyUser(req, res, next){
if(user.isAuthenticated){
return next(); //call the next middleware
}
next(err); //call the error middleware
}
错误处理程序
app.use(function(err, req, res, next) {
if(!err) return next();
res.status(500).json(new Error('error happened'));
});
然后对于每个需要身份验证的路由,在路由器中间件之前绑定(bind)VerifyUser
中间件。
由于在express中中间件顺序是相关的,因此首先将调用VerifyUser
,如果分支到达next()
调用,您的路由函数将被触发。
经过身份验证的路线:
router.get('/root', VerifyUser, function(req, res){
//if you reach this point means the user has been granted the access
})
未经身份验证的路由:
router.get('/tools', function(req, res){
})
关于javascript - Node js : How can I integrate authorization and authentication to my node application?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44079155/