Rust 中使用 Axum 实现 RBAC
本教程使用 Axum 和 casbin-rs 为用 Rust 编写的 REST API 添加基于角色的访问控制 (RBAC)。最终,三个角色(admin、editor、viewer)在不同的路由上被允许不同的 HTTP 方法,且规则位于策略文件中,您可以修改它而无需改动处理程序。
模型和策略与本教程的 Go、Node.js、Python 和 Java 版本相同。
1. 安装
cargo new rbac && cd rbac
cargo add casbin axum serde_json
cargo add tokio --features full
本教程已使用 casbin 2.20 和 axum 0.8 进行测试。
2. 编写模型
将其保存为项目根目录下的 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 = _, _:可以将用户分配给角色。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. 添加中间件
Enforcer 作为 Arc<RwLock<Enforcer>> 在请求之间共享:检查获取读锁,因此可以并行运行,而策略更改获取写锁。中间件通过 route_layer 附加,因此它仅针对存在的路由运行,未知路径仍返回 404。
src/main.rs
use std::sync::Arc;
use axum::{
extract::{OriginalUri, Path, Request, State},
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Json, Router,
};
use casbin::{CoreApi, Enforcer};
use serde_json::{json, Value};
use tokio::sync::RwLock;
type SharedEnforcer = Arc<RwLock<Enforcer>>;
/// Asks Casbin whether the current user may call this route.
async fn authorize(State(enforcer): State<SharedEnforcer>, req: Request, next: Next) -> Response {
// Replace this with the user from your session or JWT.
let user = req
.headers()
.get("x-user")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
// Inside a nested router req.uri() has the /api prefix stripped, so use the original URI.
let path = match req.extensions().get::<OriginalUri>() {
Some(OriginalUri(uri)) => uri.path().to_string(),
None => req.uri().path().to_string(),
};
let method = req.method().as_str().to_string();
match enforcer.read().await.enforce((user, path, method)) {
Ok(true) => next.run(req).await,
Ok(false) => (StatusCode::FORBIDDEN, Json(json!({ "error": "forbidden" }))).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
}
}
async fn list_articles() -> Json<Value> {
Json(json!({ "articles": [] }))
}
async fn create_article() -> (StatusCode, Json<Value>) {
(StatusCode::CREATED, Json(json!({ "created": true })))
}
async fn update_article(Path(id): Path<u32>) -> Json<Value> {
Json(json!({ "updated": id }))
}
async fn delete_article(Path(id): Path<u32>) -> Json<Value> {
Json(json!({ "deleted": id }))
}
#[tokio::main]
async fn main() {
let enforcer = Enforcer::new("model.conf", "policy.csv").await.unwrap();
let enforcer: SharedEnforcer = Arc::new(RwLock::new(enforcer));
let api = Router::new()
.route("/articles", get(list_articles).post(create_article))
.route("/articles/{id}", axum::routing::put(update_article).delete(delete_article))
.route_layer(middleware::from_fn_with_state(enforcer.clone(), authorize));
let app = Router::new().nest("/api", api).with_state(enforcer);
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
警告
在通过 nest 添加的路由器内部,req.uri() 已移除前缀:对 /api/articles 的请求到达时为 /articles,这不匹配任何策略规则。这就是为什么中间件读取 OriginalUri。如果您的中间件显示所有请求都被拒绝,请检查它传递给 Casbin 的路径。
备注
X-User 头信息使示例保持简短。Casbin 仅处理授权;在实际应用中,用户名来自您的身份验证层,例如经过验证的 JWT。
5. 试一试
cargo run
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. 运行时更改角色
角色和权限是数据。在服务器运行时,获取写锁以更改它们:
use casbin::{MgmtApi, RbacApi};
let mut e = enforcer.write().await;
e.add_role_for_user("dave", "editor", None).await?; // dave becomes an editor
e.delete_role_for_user("bob", "editor", None).await?; // bob is no longer an editor
e.add_policy(vec!["editor".into(), "/api/comments".into(), "POST".into()]).await?;
e.get_roles_for_user("alice", None); // ["admin"]
None 参数表示域;当你使用 RBAC with domains 时,请传递 Some("tenant1")。
下一步
- 将策略存储在数据库中。 用适配器(如 sqlx-adapter 或 diesel-adapter,参见 Adapters)替换
policy.csv。通过 API 进行的策略更改将自动保存。 - 现成的中间件。 axum-casbin 和 Actix 插件列在 Middleware 下。
- 基于属性的规则。 将角色与 ABAC 结合,例如“编辑只能更新自己的文章”。选择访问控制模型 展示了一个组合模型。
- gRPC 服务。 同样的思路适用于 gRPC:参见 gRPC authorization,它使用 Go,但可以直接转换为 tonic 拦截器。
- 在浏览器中实验。 将模型和策略粘贴到 online editor 中,无需运行任何代码即可测试请求。
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.