[英]Node js : How can I integrate authorization and authentication to my node application?
In my node application, I have an admin
that can make all requests and the normal user that has the right to make only certain requests. 在我的节点应用程序中,我有一个可以发出所有请求的
admin
和一个仅可以发出某些请求的普通用户。
example: 例:
admin cans make: 管理员罐头制作:
post on /root, /user, /tools
在
/root, /user, /tools
simple users can make: 简单的用户可以使:
post on /users, /tools
在
/users, /tools
If a simple user tries to make a request on /root
, he just receives and error message. 如果一个简单的用户尝试在
/root
上发出请求,他只会收到一条错误消息。
How can I handle this is node js? 我该如何处理节点js? which package, if possible few examples.
哪个包,如果可能的话几个例子。
thank 谢谢
A general approach should be define a custom middleware to verify the authentication 通用方法应定义一个自定义中间件以验证身份验证
function VerifyUser(req, res, next){
if(user.isAuthenticated){
return next(); //call the next middleware
}
next(err); //call the error middleware
}
error handler 错误处理程序
app.use(function(err, req, res, next) {
if(!err) return next();
res.status(500).json(new Error('error happened'));
});
and then for each route that needs authentication bind the VerifyUser
middleware before the router middleware. 然后为每个需要身份验证的路由在路由器中间件之前绑定
VerifyUser
中间件。 Since in express the middleware order is relevant, VerifyUser
will be called at first, and if the branch reach the next()
call your routing function will be triggered. 由于明确表示中间件顺序是相关的,因此将首先调用
VerifyUser
,如果分支到达next()
调用,则会触发您的路由功能。
Authenticated routes: 认证路线:
router.get('/root', VerifyUser, function(req, res){
//if you reach this point means the user has been granted the access
})
Non-authenticated routes: 未经认证的路由:
router.get('/tools', function(req, res){
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.