Forward authenticated user to user.page on /login uri

by Rainer Feike   Last Updated October 09, 2019 14:07 PM - source

If an authenticated user navigates to /login on a Drupal 8 site, she gets the "access denied" error. I want the site to redirect that user to /user (route user.page) instead. Unfortunately my RouteSubscriber doesn't work:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    /* @var \Symfony\Component\Routing\Route $route */
    if ($route = $collection->get('user.login')) {
      $route->setPath('/anmelden');
      $route->setRequirements([]);
      $route->setDefaults(array(
         '_controller' => '\Drupal\asdentbase\Controller\LogonController::login',
         '_title' => 'Anmelden'
       ));
    }

And my LogonController looks like

public function login() {

    if ($this->currentUser()->isAuthenticated()) {
      return $this->redirect('user.page');
    }

    $rc =
    ...

The route redirection to /anmelden works fine. But my LogonController::login function is never called for already authenticated users. There's seems to be any further magic in the core.

More detail:

I also have a route in mymodule.routing.yml like

asdentbase.login:
  path: '/anmelden'
  defaults:
    _controller: '\Drupal\asdentbase\Controller\LogonController::login'
    _title: 'Anmelden'


Answers 1


You also need to register your class in the event subscriber serivce. Create a YML similar to this:

asdentbase.services.yml

services:
  asdentbase.route_subscriber:
    class: Drupal\asdentbase\RouteSubscriber
    tags:
      - { name: event_subscriber }
Hudri
Hudri
October 09, 2019 13:54 PM

Related Questions



Error with Event Subscriber using getRouteName()

Updated May 16, 2019 16:07 PM

Alter existing route's output formats?

Updated August 19, 2019 18:07 PM

Redirect Anonymous user to login page

Updated June 20, 2017 15:07 PM

How do I redirect a user basing on its roles?

Updated June 25, 2019 18:07 PM