javascript - Node js : How can I integrate authorization and authentication to my node application?

标签 javascript node.js

在我的 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/

相关文章:

javascript - 在 Javascript 中检测 Chrome 媒体设置

javascript - 如何在输入字段上对事件监听器进行单元测试?

node.js - Mongoose 填充子文档数组

node.js - 在 IISNode 中设置多个环境变量

node.js - 在应用程序配置中找不到 URLMap 条目

javascript - 检查数字中是否存在数字

javascript - Vue 2 循环内的组件访问循环 - 实例/范围问题

javascript - 在 ECMAScript 上使用 JSDoc 和扩展语法

node.js - TypeError : firebase. 函数不是函数

json - 以 JSON 格式打印用户详细信息,如 php 中的 foreach