跳到主要内容

Node.js RBAC 教程:Express 中的基于角色的访问控制

本教程为使用 Express 构建的 REST API 添加基于角色的访问控制 (RBAC)。最终,三个角色(admin、editor、viewer)在不同的路由上被允许不同的 HTTP 方法,并且规则位于策略文件中,你可以更改这些规则而无需修改路由处理程序。

相同的 Model 和策略适用于所有 Casbin 实现,因此你可以在本教程的 Go、Python、Java 和 Rust 版本中重复使用它们。如果你使用 NestJS,请参阅 NestJS 中的 RBAC。

1. 安装​

npm init -y
npm install express casbin

2. 编写 Model​

Model 定义了请求的样子以及如何将其与策略进行匹配。将其保存为 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:每个请求包含一个用户、一个 URL 路径和一个 HTTP 方法。
  • g = _, _:用户可以被分配给角色。
  • g(r.sub, p.sub):请求的用户必须拥有策略规则中指定的角色。
  • keyMatch2 匹配诸如 /api/articles/:id 的路径,regexMatch 允许一条规则列出多个方法。有关其他内置匹配器,请参阅 函数。

3. 编写策略​

将其保存为 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

以 p 开头的行授予角色对路径和方法集的访问权限。以 g 开头的行将用户分配给角色。

4. 添加中间件​

中间件调用 enforce,传入用户、路径和方法,当 Casbin 拒绝时响应 403 Forbidden。

server.js
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();
备注

在挂载的路由器内部,req.path 不包含挂载点。req.baseUrl + req.path 提供策略所引用的完整路径(/api/articles)。

X-User 头使示例保持简短。Casbin 仅处理授权;在实际应用中,用户名来自你的身份验证层,例如已验证的 JWT 或会话。

5. 试一试​

node server.js
curl -i -X POST -H "X-User: bob" http://localhost:8080/api/articles # 201, editors can create
curl -i -X DELETE -H "X-User: bob" http://localhost:8080/api/articles/1 # 403, editors cannot delete
curl -i -X DELETE -H "X-User: alice" http://localhost:8080/api/articles/1 # 200, admins can
curl -i -X POST -H "X-User: carol" http://localhost:8080/api/articles # 403, viewers are read-only

6. 在运行时更改角色​

角色和权限是数据,因此你可以在服务器运行时更改它们:

await enforcer.addRoleForUser("dave", "editor"); // dave becomes an editor
await enforcer.deleteRoleForUser("bob", "editor"); // bob is no longer an editor
await enforcer.addPolicy("editor", "/api/comments", "POST"); // editors may now post comments

const roles = await enforcer.getRolesForUser("alice"); // ["admin"]

完整列表见 RBAC API 和 管理 API。

下一步​

  • **将策略存储在数据库中。**使用 Sequelize、TypeORM、Prisma、Mongoose 等的适配器替换 policy.csv。通过 API 进行的策略更改随后会自动保存。
  • **运行多个实例。**使用监视器,以便当一个实例更改策略时,所有实例都会重新加载该策略。
  • 显示或隐藏 UI 元素。前端用法解释了如何使用 casbin.js 将用户的权限发送到浏览器。
  • 多租户应用。带域的 RBAC 允许用户在不同的租户中拥有不同的角色。
  • **基于属性的规则。**将角色与 ABAC 结合使用,例如“编辑者只能更新自己的文章”。ABAC 教程 逐步构建了这一功能。
  • 现成的中间件。中间件列表 提供了适用于 Express、Koa、NestJS、Fastify 和其他框架的插件。

Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.