< 返回版块

向離 发表于 2021-11-08 17:39

Tags:axum

此标头指示可使用哪些身份验证方案来访问资源(以及客户端使用它们所需的任何其他信息)

有没有大佬知道怎么实现鉴权, 或者给个demo, 谢谢

评论区

写评论
作者 向離 2021-11-11 16:08

谢谢各位大佬, 还是没看懂, 继续看基础去了

Bai-Jinlin 2021-11-09 19:36

最简单的就是用现成的layer了

// curl -H "Authorization: Basic $(echo -n test:passwd | base64)" 127.0.0.1:8000
use axum::{routing::get, Router};
use tower_http::auth::RequireAuthorizationLayer;
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Ok" }))
        .layer(RequireAuthorizationLayer::basic("test", "passwd"));
    axum::Server::bind(&"127.0.0.1:8000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

而且这个还可以自定义。

use axum::http::{header, Request, Response, StatusCode};
use axum::{routing::get, Router};
use http_body::Body;
use std::marker::PhantomData;
use tower_http::auth::{AuthorizeRequest, RequireAuthorizationLayer};
struct MyAuth<ResBody> {
    _ty: PhantomData<fn() -> ResBody>,
}
impl<ResBody> Clone for MyAuth<ResBody> {
    fn clone(&self) -> Self { Self { _ty: PhantomData } }
}
impl<ResBody> AuthorizeRequest for MyAuth<ResBody>
where
    ResBody: Body + Default,
{
    type Output = ();
    type ResponseBody = ResBody;
    fn authorize<B>(&mut self, request: &Request<B>) -> Option<Self::Output> {
        let i=request.headers().get(header::AUTHORIZATION).map(|header|{
            header.to_str().ok().map(|s|s.parse::<i32>().ok()).flatten()
        }).flatten()?;
        (i%2==0).then(||())
    }
    fn unauthorized_response<B>(&mut self, _request: &Request<B>) -> Response<Self::ResponseBody> {
        let body = ResBody::default();
        let mut res = Response::new(body);
        *res.status_mut() = StatusCode::UNAUTHORIZED;
        res
    }
}
#[tokio::main]
async fn main() {
    let app =
        Router::new()
            .route("/", get(|| async { "Ok" }))
            .layer(RequireAuthorizationLayer::custom(MyAuth{ _ty: PhantomData}));
    axum::Server::bind(&"127.0.0.1:8000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

比如这样就可以用Authorization: 能被2整除的数字,验证了。

langzi.me 2021-11-08 19:37

https://github.com/tokio-rs/axum/blob/main/examples/jwt/src/main.rs 可以参考

Aya0wind 2021-11-08 18:48

给要鉴权的api路由加一个中间件,检验请求是否授权(比如是否携带有效token),加中间件的方式参考axum里的middleware和tower的layer部分,有讲怎么写一个自己的中间件。

1 共 5 条评论, 1 页