RBAC in Rust with Axum
This tutorial adds role-based access control (RBAC) to a REST API written in Rust with Axum and casbin-rs. 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 handlers.
The model and policy are the same as in the Go, Node.js, Python, and Java versions of this tutorial.
1. Install
cargo new rbac && cd rbac
cargo add casbin axum serde_json
cargo add tokio --features full
This tutorial was tested with casbin 2.20 and axum 0.8.
2. Write the model
Save this as model.conf in the project root:
[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.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를 반환합니다.
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은 인증(authorization)만 처리하며, 실제 애플리케이션에서는 사용자 이름이 검증된 JWT 등 인증(authentication) 레이어에서 제공됩니다.
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 인수는 도메인(domain)입니다. RBAC with domains를 사용하는 경우 Some("tenant1")을 전달하세요.
다음 단계
- 데이터베이스에 정책 저장.
policy.csv를 sqlx-adapter나 diesel-adapter 같은 어댑터로 교체하세요 (Adapters 참조). API를 통해 수행된 정책 변경 사항이 자동으로 저장됩니다. - 완성된 미들웨어. axum-casbin과 Actix 플러그인은 Middleware 목록에 있습니다.
- 속성 기반 규칙. 역할과 ABAC을 결합하여 예를 들어 "편집자는 자신의 기사만 업데이트할 수 있음"과 같은 규칙을 만듭니다. Choosing an access control model에서 결합 모델을 확인할 수 있습니다.
- gRPC 서비스. 동일한 아이디어가 gRPC에도 적용됩니다: Go를 사용하지만 tonic 인터셉터로 직접 변환 가능한 gRPC authorization을 참조하세요.
- 브라우저에서 실험. 모델과 정책을 online editor에 붙여넣어 코드를 실행하지 않고도 요청을 테스트하세요.
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.