I’m writing an authentication layer around my application and would like to know if I can somehow get access to the matched route or the invokable, from within the middleware. This way I can set a constant in my controller defining whether or not this request requires authentication.
I have yet to find a way to do this though, any pointers?
@ErikBooij I’ve recently implemented something similar, using a public routes array in my validation middleware. The way I access the route in the middleware is using this:
class ValidateUser {
public $publicRoutes;
public $portalUser;
public function __construct(array $publicRoutes,$user) {
$this->publicRoutes = $publicRoutes;
$this->user = $user;
}
public function __invoke($request,$response,$next) {
$routes = explode('/',$request->getUri()->getPath());
$currentRoute = $routes[1];
// if the current route isn't in the publicRoutes array, validate the user
if (!in_array($currentRoute,$this->publicRoutes)) {
// invalid user
if (empty($this->user)) {
return $response->withStatus(401);
}
}
// valid user or public route
return $next($request,$response);
}
}
@robrothedev Thanks for the reply, seems like an alright solution. I just figured out a way to do this on a controller level though, which suits my needs perfectly. I used
Thanks for replying! I don’t really want to define the authentication requirements anywhere else than in my controller, but I can imagine if that’s not an issue to you, this is a fair solution.
I find my own solution (which I’ve shown in the second post in this thread) to be be less error prone and easier to maintain. That’s largely personal preference though.
I suppose both methods are equally fine, the ->setArgument(‘auth’, false); isn’t even needed but the true is.
There are usually not a lot of admin routes that would need a “no authentication” method anyway.
Before using setArgument I was doing it allmost the same way you did though.
This is how I did it before:
public function __invoke($request, $response, $next) {
if (in_array($request->getAttribute('route')->getName(), ['admin.login', 'admin.reset']) || $this->is_authenticated) {
$response = $next($request, $response);
} else {
$response = $response->withRedirect($this->router->pathFor('admin.login'), 403);
}
return $response;
}