I have dove into the wonderful world of Rust and the Actix-Web the past few weeks and I am working on building various types of authentication through a piece of actix-web middleware. I have all of the auth logic completely figured out, but I cannot figure out how to return an unauthorized HTTP response from the middleware if a user fails an authentication check.
Here is how the Service trait is defined. Very standard from what I have seen.
impl<S, B> Service<ServiceRequest> for AuthMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>
+ 'static,
S::Future: 'static,
B: 'static
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
And here is the end of call()
where I am attempting return a particular response based on if the variable authenticate_fail
is true.
let svc = self.service.clone();
if authenticate_fail {
return Box::pin(async move {
let res = req.into_response(
HttpResponse::Unauthorized()
.finish()
);
Ok(res)
})
}
The issue I am having is that Rust yells at me because the res variable is ServiceResponse<AnyBody>
when it needs to be ServiceResponse<B>
.
Now I can see that the reason for the issue seems to lie with the fact that I am using Actix Web 4 in which the into_response()
method will return a Response object but it will have the type <AnyBody>
rather than <B>
. I know that I could go to Actix 3.3.2 to fix the issue, but I am hoping somebody might be able to either explain what I am doing incorrectly here or show me whatever is considered the correct way in Actix 4 to return an unauthorized response from middleware.
I am still very new to Rust, so I am sure that there could be something here that I am not understanding fully.
Thanks!