Add it to Cargo.toml
toml
axum = "0.5.7"
axum-casbin = "0.1.0"
tokio = { version = "1.17.0", features = [ "full" ] }
Casbin only takes charge of permission control, so you need to implement an Authentication Middleware
to identify user.
You should put axum_casbin_auth::CasbinVals
which contains subject
(username) and domain
(optional) into Extension.
For example: ```rust use axum::{response::Response, BoxError}; use futures::future::BoxFuture;
use bytes::Bytes; use http::{self, Request}; use http_body::Body as HttpBody; use std::{ boxed::Box, convert::Infallible, task::{Context, Poll}, }; use tower::{Layer, Service};
use axumcasbinauth::CasbinVals;
struct FakeAuthLayer;
impl Layer for FakeAuthLayer {
type Service = FakeAuthMiddleware;
fn layer(&self, inner: S) -> Self::Service {
FakeAuthMiddleware { inner }
}
}
struct FakeAuthMiddleware {
inner: S,
}
impl Service
where
S: Service>>::Error>,
ResBody: HttpBody + Send + 'static,
ResBody::Error: IntoBoxFuture
is a type alias for Pin<Box<dyn Future + Send + 'a>>
type Future = BoxFuture<'static, Result
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
let not_ready_inner = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, not_ready_inner);
Box::pin(async move {
let vals = CasbinVals {
subject: String::from("alice"),
domain: None,
};
req.extensions_mut().insert(vals);
inner.call(req).await
})
}
} ```
```rust use axum::{routing::get, Router}; use axumcasbinauth::{CasbinAxumLayer}; use axumcasbinauth::casbin::functionmap::keymatch2; use axumcasbinauth::casbin::{CoreApi, DefaultModel, FileAdapter, Result};
// Handler that immediately returns an empty 200 OK
response.
async fn handler() {}
async fn main() -> Result<()> { let m = DefaultModel::fromfile("examples/rbacwithpatternmodel.conf") .await .unwrap();
let a = FileAdapter::new("examples/rbac_with_pattern_policy.csv");
let casbin_middleware = CasbinAxumLayer::new(m, a).await.unwrap();
casbin_middleware
.write()
.await
.get_role_manager()
.write()
.matching_fn(Some(key_match2), None);
let app = Router::new()
.route("/pen/1", get(handler))
.route("/pen/2", get(handler))
.route("/book/:id", get(handler))
.layer(casbin_middleware)
.layer(FakeAuthLayer);
axum::Server::bind(&"127.0.0.1:8080".parse().unwrap())
.serve(app.into_make_service())
.await;
Ok(())
} ```
This project is licensed under