How can I use async in actix_web middleware and return a custom HTTP status? #3428
Answered
by
robjtede
OlalalalaO
asked this question in
Q&A
-
This is an authentication middleware. I want to return a 403 status directly when the permission check fails.The This is my code, but it is incorrect: impl<S, B> Transform<S, ServiceRequest> for Auth
where
S: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = AuthMiddle<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(AuthMiddle { service }))
}
}
pub struct AuthMiddle<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for AuthMiddle<S>
where
S: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let fut = async move {
if check_permission(&req).await {
self.service.call(req).await
} else {
let (request, _pl) = req.into_parts();
let response = HttpResponse::Forbidden().finish().map_into_boxed_body();
Ok(ServiceResponse::new(request, response))
}
};
Box::pin(fut)
}
} The error is as follows:
What should I do? |
Beta Was this translation helpful? Give feedback.
Answered by
robjtede
Jul 20, 2024
Replies: 1 comment
-
For your case, you'd need to leverage type Response = ServiceResponse<EitherBody<B, BoxBody>> However, the easiest way to create async middleware these days is to use |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
robjtede
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For your case, you'd need to leverage
EitherBody
.However, the easiest way to create async middleware these days is to use
middleware::from_fn
from the lab (soon to graduate to the main lib). I'd recommend using this instead.