Node.js + Express.js 用户权限安全模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9609325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:18:03  来源:igfitidea点击:

Node.js + Express.js User Permission Security Model

securitynode.jsexpress

提问by Travis Parks

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.

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

回答by Linus Gustav Larsson Thiel

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"));

回答by Clément Renaud

You can use ability-js with everyauth, which is quite similar to CanCan for Rails https://github.com/scottkf/ability-js

您可以在everyauth中使用ability-js,这与CanCan for Rails非常相似https://github.com/scottkf/ability-js

回答by McMeep

Take a look at this listfor NodeJS ACL/Permission systems. IMHO OptimalBits node_acllooks best.

看看这个NodeJS ACL/权限系统列表。恕我直言OptimalBits node_acl看起来最好。

回答by Tommz

There is now Node module permissionfor this. It's very easy to use, very similar to accepted answer, but still some features are added.

现在有节点模块权限。它非常易于使用,与接受的答案非常相似,但仍添加了一些功能。