js用户权限安全模型

js用户权限安全模型

本文介绍了Node.js + Express.js用户权限安全模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个应用程序有两种类型的用户。取决于用户登录的方式,我们希望他们能够访问应用程序的不同部分。



我们如何实现安全模型,以防止用户看到他们没有访问权限?



我们是否使每个路由实现的安全性?问题是我们将在请求之间有一些重复的逻辑。我们可以将其移动到帮助函数中,但是我们仍然需要记住调用它。



我们使安全性是全局app.all()路由处理程序的一部分?问题在于,我们必须检查每条路线,并根据众多规则执行不同的逻辑。至少所有的代码都在一个地方,但是所有代码都在一个地方。

解决方案

拥有每条路线通常适用于我。这是我通常做的:

  function requireRole(role){
return function(req,res,next) {
if(req.session.user&& req.session.user.role === role){
next();
} else {
res.send(403);
}
}
}

app.get(/ foo,foo.index);
app.get(/ foo /:id,requireRole(user),foo.show);
app.post(/ foo,requireRole(admin),foo.create);

//所有栏都受保护
app.all(/ foo / bar,requireRole(admin));

//以/ foo / bar /开头的所有路径都被保护
app.all(/ foo / bar / *,requireRole(user));


We have an application that has two types of users. Depending on how the user logs in, we want them to have access to different parts of the application.

How do we implement a security model for preventing users from seeing things they do not have access to?

Do we make security part of each routes implementation? The problem being that we will have some duplicate logic across requests. We could move this into helper functions, but we'd still need to remember to call it.

Do we make security part of a global app.all() route handler? The problem being that we have to inspect each route and do different logic based on a multitude of rules. At least all the code is in one place, but then... all the code is in one place.

解决方案

Having it per-route usually works for me. This is what I typically do:

function requireRole (role) {
    return function (req, res, next) {
        if (req.session.user && req.session.user.role === role) {
            next();
        } else {
            res.send(403);
        }
    }
}

app.get("/foo", foo.index);
app.get("/foo/:id", requireRole("user"), foo.show);
app.post("/foo", requireRole("admin"), foo.create);

// All bars are protected
app.all("/foo/bar", requireRole("admin"));

// All paths starting with "/foo/bar/" are protected
app.all("/foo/bar/*", requireRole("user"));

这篇关于Node.js + Express.js用户权限安全模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:08