I want to redirect an anonymous user to the login form if such user encounters a 403 error.
I have created event subscriber and this is my code, but I end up on loop on the current page.
/** * Redirect anonymous user to login page if he encounters 404 or 403 * response. * * @param SymfonyComponentHttpKernelEventGetResponseEvent $response * The created response object that will be returned. * @param string $event * The string representation of the event. * @param DrupalComponentEventDispatcherContainerAwareEventDispatcher $event_dispatcher * Event dispatcher that lazily loads listeners and subscribers from the dependency injection * container. */ public function checkLoginNeeded(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) { $routeMatch = RouteMatch::createFromRequest($response->getRequest()); $route_name = $routeMatch->getRouteName(); $is_anonymous = Drupal::currentUser()->isAnonymous(); $is_not_login = $route_name != 'user.login'; if ($is_anonymous && $route_name == 'system.403' && $is_not_login) { $query = $response->getRequest()->query->all(); // $query['destination'] = $routeMatch->getRouteObject()->getPath(); $query['destination'] = Drupal::url('<current>'); $login_uri = Drupal::url('user.login', [], ['query' => $query]); $returnResponse = new RedirectResponse($login_uri, Response::HTTP_FOUND); $response->setResponse($returnResponse); } }
I think this is related to the fact that the response already contains destination(current uri) and system.404 and system.403 have some high priority that prevent me to override this.