节点js:如何将授权和身份验证集成到我的节点应用程序中?

时间:2017-05-19 21:21:00

标签: javascript node.js

在我的节点应用程序中,我有一个admin可以发出所有请求,而普通用户有权只发出某些请求。

示例:

admin cans make:

发布在/root, /user, /tools

简单的用户可以:

发布在/users, /tools

如果一个简单的用户试图在/root上发出请求,他就会收到并收到错误消息。

我如何处理这是节点js?哪个包,如果可能的话很少。

感谢

1 个答案:

答案 0 :(得分:1)

一般方法应定义自定义中间件以验证身份验证

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'));
});

然后对于需要身份验证的每个路由绑定路由器中间件之前的VerifyUser中间件 。 由于在表达中间件顺序是相关的,因此首先会调用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){

})
相关问题