Auth Middleware in Slim 4

Hi Odan,

Thank you very much, we tried the below

  • Removing the line “$response = $handler->handle($request);” and tried with other 2 lines no luck - Blank page - Slim\Exception\HttpNotFoundException \n Code: 404
  • Vice versa too, still no luck - Blank page - Slim\Exception\HttpNotFoundException \n Code: 404
  • Added the base path middle ware for both the test.

At last option can you please check whether the placement of “.htaccess” file is correct, based on the below setup.

/var/www/test
  .htaccess
  Smil4
     	composer.json  composer.lock  source  vendor
  config
  public
    	.htaccess index.php
  template
  temp

middleware.php

<?php

use Selective\Config\Configuration;
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use Slim\Views\TwigMiddleware;
use Slim\Middleware\RoutingMiddleware;
use Selective\BasePath\BasePathMiddleware;

require_once('bpauthurization.php');

return function (App $app) {
       $routingMiddleware = new Slim\Middleware\RoutingMiddleware(
                $app->getRouteResolver(),
                $app->getRouteCollector()->getRouteParser()
       );
       $app->add(new authorization());
       $app->addBodyParsingMiddleware();
       $app->addMiddleware($routingMiddleware);
       $app->add(new BasePathMiddleware($app));
       $app->add(TwigMiddleware::createFromContainer($app));
       $app->add(ErrorMiddleware::class);
};
?>

authorization.php

<?php
use Slim\Routing\RouteContext;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Exception\NotFoundException;
use Nyholm\Psr7\Factory\Psr17Factory;
class authorization {
      public function __invoke($request, $handler): Response {
                      $routeContext = RouteContext::fromRequest($request);
                      $route = $routeContext->getRoute();
                      if(empty($route)) { throw new NotFoundException($request, $response); }
                      $routeName = $route->getName();
                      $publicRoutesArray = array('f401');
                      if(empty($_SESSION['user']) && (in_array($routeName, $publicRoutesArray))) {
                         $routeParser = RouteContext::fromRequest($request)->getRouteParser();
                         $url = $routeParser->urlFor('login');
                         $responseFactory = new \Nyholm\Psr7\Factory\Psr17Factory();
                         $response = $responseFactory->createResponse(200);
                         return $response->withHeader('Location', $url)->withStatus(302);
                      } else { $response = $handler->handle($request); }
             return $response;
      }
}