跳到主要内容

Python RBAC 教程:FastAPI 中的基于角色的访问控制

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

相同的 Model 和策略适用于所有 Casbin 实现,因此你可以在本教程的 Go、Node.js、Java 和 Rust 版本中重复使用它们。

1. 安装​

pip install casbin fastapi uvicorn

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 允许一条规则列出多个方法。有关其他内置匹配器,请参阅 Functions。

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. 添加依赖项​

FastAPI 依赖项使用用户、路径和方法调用 enforce,当 Casbin 拒绝时抛出 403 Forbidden。在应用上注册该依赖项会将其应用于所有路由。

main.py
import casbin
from fastapi import Depends, FastAPI, HTTPException, Request

enforcer = casbin.Enforcer("model.conf", "policy.csv")


def authorize(request: Request) -> None:
"""Ask Casbin whether the current user may call this route."""
# Replace this with the user from your session or JWT.
user = request.headers.get("X-User", "")

if not enforcer.enforce(user, request.url.path, request.method):
raise HTTPException(status_code=403, detail="forbidden")


app = FastAPI(dependencies=[Depends(authorize)])


@app.get("/api/articles")
def list_articles():
return {"articles": []}


@app.post("/api/articles", status_code=201)
def create_article():
return {"created": True}


@app.put("/api/articles/{article_id}")
def update_article(article_id: int):
return {"updated": article_id}


@app.delete("/api/articles/{article_id}")
def delete_article(article_id: int):
return {"deleted": article_id}
备注

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

5. 试一试​

uvicorn main:app --port 8080
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. 运行时更改角色​

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

enforcer.add_role_for_user("dave", "editor") # dave becomes an editor
enforcer.delete_role_for_user("bob", "editor") # bob is no longer an editor
enforcer.add_policy("editor", "/api/comments", "POST") # editors may now post comments

enforcer.get_roles_for_user("alice") # ['admin']

完整列表请参见 RBAC API 和 Management API。

下一步​

  • 将策略存储在数据库中。 将 policy.csv 替换为适用于 SQLAlchemy、Django ORM、MongoDB、Redis 等的 适配器。通过 API 进行的策略更改将自动保存。
  • 运行多个工作进程。 使用 监视器,以便当一个进程更改策略时,所有进程都会重新加载策略。
  • 多租户应用。 带域的 RBAC 可以让用户在不同租户中拥有不同的角色。
  • 基于属性的规则。 将角色与 ABAC 结合使用,例如“编辑只能更新自己的文章”。ABAC 教程 逐步构建此功能。
  • 现成的中间件。 中间件列表 提供了适用于 FastAPI、Django、Flask 和其他框架的插件。
  • 在浏览器中实验。 将模型和策略粘贴到 在线编辑器 中以测试请求,无需运行任何代码。

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