Actix-web middleware redirect with extension data, please help

What your middleware is doing is basically redirecting your user to /login in case they aren't logged in (is_logged_in == false) and not trying to access /login to begin with (which would cause an endless loop where your server responds to a request for /login with "yes, you can access /login, but first visit /login to authenticate yourself").

So

is pretty much working like a normal function with an early return where you respond to your client with a http response with status code 302, without ever entering the handler for the route the user was trying to access.

The workflow is basically like this:

  1. Your client asks your server to access /some_route
  2. Your server calls your login middleware
  3. Your middleware sees the user is not logged in and therefore is not allowed to call this route. We respond to the client with a redirection to /login (that's what is happening in the if statement of your middleware)
  4. Your client (probably a web browser like Chrome or Firefox) sees the redirect. It looks where it should redirect to (the location header of the http response)
  5. Your client makes a new http request to /login. This new request is completely independent of the first request we made. Your middleware will be called anew and this time it will not enter the if statement, because the user—even though they are still not signed in—is trying to access /login this time.
  6. Your middleware adds the Msg as an extension to the request
  7. Your middleware continues by passing the request to your /login handler (let res = self.service.call(request);
  8. Your /login handler extracts Msg, does something with it and returns some http response to the client

Hope that helps you in understanding what your middleware is doing there.

1 Like