跳到主要内容

Node.js Express 中的 ABAC

基于角色的访问控制回答了“编辑者可以做什么?”的问题。许多实际规则需要的不仅仅是角色:作者可以编辑自己的草稿,编辑者可以编辑自己部门的文章,任何人都可以阅读已发布的文章。这些规则依赖于用户和资源的属性,这正是基于属性的访问控制(ABAC)的用途。

本教程使用 Express 构建一个小型文章 API,并将所有这些规则放入 Casbin 策略文件中。相同的模型和策略在本教程的 Go 和 Python 版本中无需修改即可工作。如果你仍在 RBAC 和 ABAC 之间做选择,请先阅读 选择访问控制模型。

1. 安装​

npm install casbin express

2. 编写模型​

将此内容保存为 model.conf:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub_rule, obj_type, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.obj.Type == p.obj_type && r.act == p.act && eval(p.sub_rule)
  • r.sub 和 r.obj 是普通的 JavaScript 对象。匹配器读取它们的属性,例如 r.obj.Type。
  • 每条策略规则在 sub_rule 中携带一个条件。eval(p.sub_rule) 针对请求评估该条件,因此规则存在于策略中而不是模型中。

3. 编写策略​

将此内容保存为 policy.csv:

p, r.obj.Status == 'published', article, read
p, r.sub.Name == r.obj.Owner, article, read
p, r.sub.Name == r.obj.Owner && r.obj.Status == 'draft', article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, publish

将每一行读作“当条件为真时,允许对文章执行此操作”:

  1. 任何人都可以阅读已发布的文章。
  2. 作者可以阅读自己的文章,包括草稿。
  3. 作者可以在文章处于草稿状态时编辑自己的文章。
  4. 编辑者可以编辑自己部门的任何文章。
  5. 编辑者可以发布自己部门的文章。
提示

在条件中使用单引号书写字符串字面量,例如 'published'。字段中间的 double quote 会破坏 CSV 解析。如果条件需要逗号,请用双引号包裹整个字段。

4. 添加中间件​

ABAC 需要资源本身,而不仅仅是其 URL。authorize 中间件加载文章,询问 Casbin,并将文章放在 req 上,这样路由 handler 就不必再次加载它。

app.js
const express = require('express');
const { newEnforcer } = require('casbin');

// In a real application these come from your database.
const users = {
alice: { Name: 'alice', Role: 'author', Department: 'engineering' },
bob: { Name: 'bob', Role: 'editor', Department: 'engineering' },
carol: { Name: 'carol', Role: 'editor', Department: 'sales' },
dave: { Name: 'dave', Role: 'author', Department: 'engineering' },
};

const articles = {
1: { Type: 'article', Id: '1', Title: 'Draft by alice', Owner: 'alice', Department: 'engineering', Status: 'draft' },
2: { Type: 'article', Id: '2', Title: 'Published by alice', Owner: 'alice', Department: 'engineering', Status: 'published' },
};

// Loads the article, then asks Casbin whether the current user may perform `action` on it.
function authorize(enforcer, action) {
return async (req, res, next) => {
// Replace this with the user from your session or JWT.
const user = users[req.get('X-User')];
if (!user) {
return res.status(401).json({ error: 'unauthenticated' });
}
const article = articles[req.params.id];
if (!article) {
return res.status(404).json({ error: 'not found' });
}
if (!(await enforcer.enforce(user, article, action))) {
return res.status(403).json({ error: 'forbidden' });
}
req.article = article;
next();
};
}

async function main() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');

const app = express();
app.use(express.json());

app.get('/articles/:id', authorize(enforcer, 'read'), (req, res) => {
res.json(req.article);
});
app.put('/articles/:id', authorize(enforcer, 'update'), (req, res) => {
req.article.Title = req.body?.title ?? req.article.Title;
res.json(req.article);
});
app.post('/articles/:id/publish', authorize(enforcer, 'publish'), (req, res) => {
req.article.Status = 'published';
res.json(req.article);
});

app.listen(3000, () => console.log('listening on http://localhost:3000'));
}

main();
备注

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

5. 尝试运行​

node app.js

文章 1 是 alice 的草稿,文章 2 是她已发布的文章,两者都属于工程部门。

curl -i -H "X-User: dave" http://localhost:3000/articles/1 # 403, someone else's draft
curl -i -H "X-User: dave" http://localhost:3000/articles/2 # 200, published
curl -i -X PUT -H "X-User: alice" -H "Content-Type: application/json" \
-d '{"title":"New title"}' http://localhost:3000/articles/1 # 200, her own draft
curl -i -X PUT -H "X-User: alice" http://localhost:3000/articles/2 # 403, no longer a draft
curl -i -X PUT -H "X-User: bob" http://localhost:3000/articles/2 # 200, editor in engineering
curl -i -X PUT -H "X-User: carol" http://localhost:3000/articles/2 # 403, editor in sales
curl -i -X POST -H "X-User: alice" http://localhost:3000/articles/1/publish # 403, authors cannot publish
curl -i -X POST -H "X-User: bob" http://localhost:3000/articles/1/publish # 200
curl -i -H "X-User: dave" http://localhost:3000/articles/1 # 200, now published

6. 在运行时更改规则​

条件是策略行,因此可以在服务器运行时添加和删除它们,并通过 adapter 保存到数据库:

// Admins may edit any article.
await enforcer.addPolicy("r.sub.Role == 'admin'", 'article', 'update');

// Which rule allowed this request? Useful for audit logs.
const [ok, rule] = await enforcer.enforceEx(users.bob, articles[2], 'update');
// true [ "r.sub.Role == 'editor' && r.sub.Department == r.obj.Department", 'article', 'update' ]

ABAC 还是 RBAC?​

  • 当权限遵循职能角色且不依赖于被访问的具体记录时,使用 RBAC。它更易于审计:“列出编辑者可以做的一切”是一个简单的查询。参见 Node.js 中的 RBAC 教程。
  • 当答案取决于记录本身时,使用 ABAC:例如记录的所有者、部门、状态或敏感度。
  • 大多数应用结合使用两者:角色决定用户可以访问哪些功能,属性进一步缩小他们可以触及的记录范围。访问控制模型对比 展示了一个组合模型。

下一步​

  • 完整的 ABAC 参考。 ABAC 详细介绍了 JSON 请求参数、引用规则和 eval()。
  • NestJS。NestJS 教程展示了一个守卫和一个装饰器,你可以使用相同的 ABAC 模型对其进行扩展。
  • 在浏览器中检查权限。Casbin.js使用相同的规则在前端显示或隐藏按钮。
  • 在浏览器中进行实验。在线编辑器可以使用 JSON 属性评估 ABAC 请求。

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