【发布时间】:2020-01-13 12:16:25
【问题描述】:
我的客户通过Authorization 标头中的令牌进行授权,每个请求都需要检查该令牌。如果这个header丢失或者找不到对应的用户,我想返回HTTP代码Unauthorized,否则我想正常处理请求。
目前我有很多重复的代码,因为我在每个请求处理程序中检查这个标头。
actix docs 在第一段中建议halt request processing to return a response early 是可能的。
如何实现?
由于我没有找到实现此行为的示例,我尝试提出自己的中间件函数,但无法编译。
为了克服返回两种不同类型(ServiceResponse 和Map)的问题,我已经将返回值装箱,所以How do I conditionally return different types of futures? 中提出的问题不是问题。更重要的是,我不知道该 wrap_fn 函数的返回值究竟需要哪些类型的 trait 实现。我现在拥有的那些不起作用。
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>>`
【问题讨论】:
-
请粘贴您收到的准确和完整的错误 - 这将有助于我们了解问题所在,以便我们提供最佳帮助。有时试图解释错误消息很棘手,实际上错误消息的不同部分很重要。
-
看来How do I conditionally return different types of futures? 的答案可能会回答您的问题。如果没有,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
标签: server rust rust-actix actix-web