RBAC in Node.js with Express
This tutorial adds role-based access control (RBAC) to a REST API built with Express. At the end, three roles (admin, editor, viewer) are allowed different HTTP methods on different routes, and the rules live in a policy file that you can change without touching the route handlers.
The same model and policy work in every Casbin implementation, so you can reuse them in the Go, Python, and Java versions of this tutorial.
1. Install
npm init -y
npm install express casbin
2. Write the model
The model says what a request looks like and how it is matched against the policy. Save this as model.conf:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)
r = sub, obj, act: each request is a user, a URL path, and an HTTP method.g = _, _: users can be assigned to roles.g(r.sub, p.sub): the request's user must have the role named in the policy rule.keyMatch2matches paths such as/api/articles/:id, andregexMatchlets one rule list several methods. See Functions for the other built-in matchers.
3. Write the policy
Save this as policy.csv:
p, admin, /api/*, (GET)|(POST)|(PUT)|(DELETE)
p, editor, /api/articles, (GET)|(POST)
p, editor, /api/articles/:id, (GET)|(PUT)
p, viewer, /api/articles, GET
p, viewer, /api/articles/:id, GET
g, alice, admin
g, bob, editor
g, carol, viewer
Lines starting with p grant a role access to a path and a set of methods. Lines starting with g assign users to roles.
4. Add the middleware
The middleware calls enforce with the user, the path, and the method, and responds with 403 Forbidden when Casbin says no.
const express = require("express");
const { newEnforcer } = require("casbin");
// authorize asks Casbin whether the current user may call this route.
function authorize(enforcer) {
return async (req, res, next) => {
// Replace this with the user from your session or JWT.
const user = req.get("X-User") || "";
try {
const allowed = await enforcer.enforce(user, req.baseUrl + req.path, req.method);
if (!allowed) {
return res.status(403).json({ error: "forbidden" });
}
next();
} catch (err) {
next(err);
}
};
}
async function main() {
const enforcer = await newEnforcer("model.conf", "policy.csv");
const app = express();
const api = express.Router();
api.get("/articles", (req, res) => res.json({ articles: [] }));
api.post("/articles", (req, res) => res.status(201).json({ created: true }));
api.put("/articles/:id", (req, res) => res.json({ updated: req.params.id }));
api.delete("/articles/:id", (req, res) => res.json({ deleted: req.params.id }));
app.use("/api", authorize(enforcer), api);
app.listen(8080, () => console.log("listening on :8080"));
}
main();
Inside a mounted router, req.path does not include the mount point. req.baseUrl + req.path gives the full path (/api/articles) that the policy refers to.
The X-User header keeps the example short. Casbin handles authorization only; in a real application the user name comes from your authentication layer, such as a verified JWT or a session.