alexw
alexw

Reputation: 8688

What is the correct way to redirect a request in middleware?

I am trying to implement the (in)famous improved persistent session as middleware in the Slim microframework.

There are some places in the algorithm described where the application should check the user's cookie and redirect the user if their cookie has expired or is invalid. Unfortunately, it is impossible to redirect a user from within middleware, for two reasons:

  1. Slim's redirect can only be used within named routes;
  2. redirect will create an entirely new request, thus restarting the Slim application. The same conditions that triggered the redirect before will be re-triggered, thus creating an infinite loop.

Problem 1 can be solved with clever use of hooks, but I am not sure what to do about problem 2. I notice that some middleware solves this by using a custom Exception, which they then catch with Slim's error handler, and then call the redirect:

// Handle the possible 403 the middleware can throw
$app->error(function (\Exception $e) use ($app) {
    ...
    if ($e instanceof HttpUnauthorizedException) {
        return $app->redirectTo('login');
    }
    ...
});

But I am not certain that this is the best way to do it. Are there any other ways that I can accomplish this?

Upvotes: 1

Views: 346

Answers (1)

Ben Fried
Ben Fried

Reputation: 2204

What you listed above is a perfectly fine way of doing it, and is generally how it's done. Assuming your login page doesn't check for HttpUnauthorizedExcepion, there would be no way it could ever redirect loop.

Upvotes: 1

Related Questions