Node.js + Express.js User Permission Security Model

Securitynode.jsExpress

Security Problem Overview


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.

Security Solutions


Solution 1 - Security

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

Solution 2 - Security

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

Solution 3 - Security

Take a look at this list for NodeJS ACL/Permission systems. IMHO OptimalBits node_acl looks best.

Solution 4 - Security

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTravis ParksView Question on Stackoverflow
Solution 1 - SecurityLinus ThielView Answer on Stackoverflow
Solution 2 - SecurityClément RenaudView Answer on Stackoverflow
Solution 3 - SecurityMcMeepView Answer on Stackoverflow
Solution 4 - SecurityTommzView Answer on Stackoverflow