4 个版本 (2 个稳定版)
1.1.0 | 2024年2月27日 |
---|---|
1.0.0 | 2024年2月26日 |
0.1.1 | 2022年12月14日 |
0.1.0 | 2022年12月13日 |
#117 in 认证
每月下载量62次
14KB
161 代码行
axum-casbin
安装
在 Cargo.toml
中添加依赖
cargo add axum
cargo add axum-casbin
cargo add tokio --features full
要求
Casbin 仅负责权限控制,因此您需要实现一个 Authentication Middleware
来识别用户。
您应该将包含 subject
(用户名) 和 domain
(可选) 的 axum_casbin::CasbinVals
放入 扩展 中。
例如
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 axum_casbin::CasbinVals;
#[derive(Clone)]
struct FakeAuthLayer;
impl<S> Layer<S> for FakeAuthLayer {
type Service = FakeAuthMiddleware<S>;
fn layer(&self, inner: S) -> Self::Service {
FakeAuthMiddleware { inner }
}
}
#[derive(Clone)]
struct FakeAuthMiddleware<S> {
inner: S,
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for FakeAuthMiddleware<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>, Error = Infallible>
+ Clone
+ Send
+ 'static,
S::Future: Send + 'static,
ReqBody: Send + 'static,
Infallible: From<<S as Service<Request<ReqBody>>>::Error>,
ResBody: HttpBody<Data = Bytes> + Send + 'static,
ResBody::Error: Into<BoxError>,
{
type Response = S::Response;
type Error = S::Error;
// `BoxFuture` is a type alias for `Pin<Box<dyn Future + Send + 'a>>`
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
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
})
}
}
示例
use axum::{routing::get, Router};
use axum_casbin::{CasbinAxumLayer};
use axum_casbin::casbin::function_map::key_match2;
use axum_casbin::casbin::{CoreApi, DefaultModel, FileAdapter, Result};
// Handler that immediately returns an empty `200 OK` response.
async fn handler() {}
#[tokio::main]
async fn main() -> Result<()> {
let m = DefaultModel::from_file("examples/rbac_with_pattern_model.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(())
}
许可证
本项目受
- Apache License, Version 2.0 (LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0) 许可
依赖
~14–28MB
~411K SLoC