如何从actix-web中间件返回早期响应?

时间:2019-09-11 15:55:01

标签: server rust rust-actix actix-web

我的客户通过Authorization标头中的令牌进行授权,需要针对每个请求进行检查。如果缺少此标头或找不到相应的用户,我想返回HTTP代码Unauthorized,否则我想正常处理请求。

当前,我有很多重复的代码,因为我正在每个请求处理程序中检查此标头。 actix docs在第一段中建议可以halt request processing to return a response early。 如何实现?

由于我还没有找到实现此行为的示例,因此我尝试提出自己的中间件功能,但无法编译。

我已经装箱了返回值,以解决返回两种不同类型(ServiceResponseMap)的问题,因此How do I conditionally return different types of futures?中提出的问题不是问题。我不知道更多的是,确切需要哪种类型的特征实现作为此wrap_fn函数的返回值。我现在拥有的那些不起作用。

App::new()
    .wrap(Cors::new().allowed_origin("http://localhost:8080"))
    .register_data(state.clone())
    .service(
        web::scope("/routing")
            .wrap_fn(|req, srv| {
                let unauth: Box<dyn IntoFuture<Item = ServiceResponse>> = Box::new(ServiceResponse::new(req.into_parts().0, HttpResponse::Unauthorized().finish()));
                let auth_header = req.headers().get("Authorization");
                match auth_header {
                    None => unauth,
                    Some(value) => {
                        let token = value.to_str().unwrap();
                        let mut users = state.users.lock().unwrap();
                        let user_state = users.iter_mut().find(|x| x.auth.token == token);
                        match user_state {
                            None => unauth,
                            Some(user) => {
                                Box::new(srv.call(req).map(|res| res))
                            }
                        }
                    }
                }
            })
            .route("/closest", web::get().to(routing::find_closest))
            .route("/fsp", web::post().to(routing::fsp))
            .route("/preference", web::get().to(routing::get_preference))
            .route("/preference", web::post().to(routing::set_preference))
            .route("/find_preference", web::post().to(routing::find_preference))
            .route("/reset", web::post().to(routing::reset_data)),
    )
    .bind("0.0.0.0:8000")
    .expect("Can not bind to port 8000")
    .run()
    .expect("Could not start sever");

我在编译时遇到两个错误。

1。

error[E0191]: the value of the associated types `Future` (from the trait `futures::future::IntoFuture`), `Error` (from the trait `futures::future::IntoFuture`) must be specified
  --> src/server/mod.rs:36:41
   |
36 |                         let unauth: Box<dyn IntoFuture<Item = ServiceResponse>> =
   |                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |                                         |
   |                                         associated type `Future` must be specified
   |                                         associated type `Error` must be specified

2。

error[E0277]: the trait bound `dyn futures::future::IntoFuture<Item = actix_web::service::ServiceResponse>: futures::future::Future` is not satisfied
  --> src/server/mod.rs:35:22
   |
35 |                     .wrap_fn(|req, srv| {
   |                      ^^^^^^^ the trait `futures::future::Future` is not implemented for `dyn futures::future::IntoFuture<Item = actix_web::service::ServiceResponse>`
   |
   = note: required because of the requirements on the impl of `futures::future::Future` for `std::boxed::Box<dyn futures::future::IntoFuture<Item = actix_web::service::ServiceResponse>>`

2 个答案:

答案 0 :(得分:1)

您可以创建自己的类型Authorized,为其实现FromRequest,并将Authorized定义为应检查授权的处理程序中的参数。

简化示例:

use actix_web::dev::Payload;
use actix_web::error::ErrorUnauthorized;
use actix_web::{web, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer};

fn main() {
    HttpServer::new(move || App::new().route("/", web::to(index)))
        .bind("127.0.0.1:3000")
        .expect("Can not bind to '127.0.0.1:3000'")
        .run()
        .unwrap();
}

fn index(_: Authorized) -> HttpResponse {
    HttpResponse::Ok().body("authorized")
}

struct Authorized;

impl FromRequest for Authorized {
    type Error = Error;
    type Future = Result<Self, Error>;
    type Config = ();

    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        if is_authorized(req) {
            Ok(Authorized)
        } else {
            Err(ErrorUnauthorized("not authorized"))?
        }
    }
}

fn is_authorized(req: &HttpRequest) -> bool {
    if let Some(value) = req.headers().get("authorized") {
        // actual implementation that checks header here
        dbg!(value);
        true
    } else {
        false
    }
}

此代码产生:

$ curl localhost:3000
not authorized⏎
$ curl localhost:3000 -H 'Authorized: i am root'
authorized⏎

您可能会对中间件做同样的事情,但是我对中间件抽象一无所知。另外,您可能想向处理程序提供有用的信息,例如用户名:

struct Authorized {
    username: String
}

答案 1 :(得分:1)

我参加聚会有点晚,但是从Actix中间件中做到这一点的最佳方法是使用futures::future::Either。您可以在这里查看其用法:https://github.com/actix/examples/blob/master/middleware/src/redirect.rs

Either的左侧将是Future,它将响应传递到链中的下一个阶段。如果您希望提早返回响应,则右侧为响应(通常为HttpResponse)。