Middleware redirect before route

Hi!

I’m new to Slim. I’ve started to learning and I would like to redirect to login page from middleware, but it not realy works. What’s wrong with my code?

Routing:

$app->group("/admin", function (RouteCollectorProxy $group){

    $group->get("[/]", [dashboardController::class, "viewDashboard"]);
    
    $group->get("/blog[/]", [blogController::class, "viewBlog"]);

    $group->get("/login[/]", [userController::class, "viewlogin"]);
    
    $group->post("/login/auth[/]", [userController::class, "authUser"]);

})->add(permissionMiddleware::class);

permissionMiddleware:

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;

class permissionMiddleware
{    
    public function __invoke(Request $request, RequestHandler $handler)
    {
        $routeContext = RouteContext::fromRequest($request);
        $route = $routeContext->getRoute();
        
        $pattern = $route->getPattern();
        var_dump($pattern);
        
        //loging and login/auth are allowed without permission
        if(preg_match("/^\/admin\/login\/?(\/auth\/?|$)/", $pattern)){
            return $handler->handle($request);
        }
        
        //user has auth session
        if(isset($_SESSION["user_auth"]))
            return $handler->handle($request);
        
        
        //no session and no login request redirect to admin/login
        $response = $handler->handle($request);
        return $response->withStatus(302)->withHeader('Location', '/nt-slim/admin/login');
    }
}

I get this error in my browser:

var_dump($pattern);

This line will send some data to the output buffer and could be an issue for the browser when you send a redirect header. Please try to remove this line first.

Thanks! I’ve removed the var_dump() but I got the same error.

I’ve tested the code again since last night. When I move out from the group the /admin/login and /admin/login/auth routes, then the redirect works well, but I don’t understand why.

If somebody could tell me why was it wrong I would appreciate it. I’m planning to switch to slim that’s why I try to understand.

My guess is that it has to do with the way you define the routes (and the regex within the middleware may also be an issue).
You should not define the [/] in your routes. The routing in Slim should work without it.

Thanks! I’ve got 404 errors without it when I had a trailing slash in the url.
I prefer to use url-s without trailing slash also. I dunno yet how to rtrim() it.

In this case, there is something incorrect with the configuration of the web server. Please check this page:

https://www.slimframework.com/docs/v4/start/web-servers.html#apache-configuration

If you want to redirect from a middleware you need to return a redirect response directly instead of executing the rest of the middleware stack and the route handler.

So something like:

public function __invoke(Request $request, Handler $handler): Response
{
    // If  auth success run the next thing in the stack
    if ($authSuccess === true) {
        return $handler->handle($request);
    }

    // Return a new redirection response instead of the next thing in the stack
    return (new ResponseFactory)
        ->createResponse(302)
        ->withHeader('Location', '/nt-slim/admin/login');
}

Thanks! It’s working!