Search code examples
phpauthenticationmiddlewareslim-3

Slim Authentication middleware for all routes except someone


I would like to have a Slim middleware to check authentication on all requests but some specific ones (for example login page). I prepared the first AuthenticationMiddleware middleware to check all pages:

$app->add(new \App\Middleware\AuthenticationMiddleware($container));

Then I create another one AnonymousMiddleware that it is supposed to add a variable to set the exception to authentication checks:

$app->group('',function() use ($app){
    $app->get('/','LogicController:index');    
})->add(new AnonymousMiddleware($container));

The problem is that routes middleware (AnonymousMiddleware) is applied AFTER the general middleware (AuthenticationMiddleware);

I tried to use determineRouteBeforeAppMiddleware but it doesn't change the result.

I know I would set a route middleware for all authenticated routes but sounds a bit dangerous if I forget it, so, I would prefer to set which router are not under authentication then keep the check all other routes.


Solution

  • you need to chose different approach

    you need to wrap all routes which should be "protected via Auth middleware" and exclude = not wrap routes which should not be handled by this middleware

    you can add a group where all your routes will live and only login (and logout) route will be outside of this group ;)

    something like

    $app->group("/api/v1", function() { 
     // all your protected routes definitions here
    })
    ->add(AuthenticationMiddleware::class)); // wrap by middleware
    
    $app->post('/login', function(){});
    
    $app->add(new MiddlewareForAllRoutes()); // middlewares for all routes