除了某人之外的所有路由的Slim Authentication中间件

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.

1个回答

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
dongzouya5792
dongzouya5792 是的,谢谢似乎没有其他选择来反转逻辑。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐