Feb 10, 2021 in Drupal 8

An often use case for dashboards or software behind a login is to redirect anonymous users to the login page. Like always, I do not want to use contributed modules for this. I found a nice answer on Drupal answers, but it was lacking a few things. This snippet takes also other user routes into account and works for drupal 9 as well. 

First, in mymodule.services.yml:

    class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
    arguments: []
      - {name: event_subscriber}

Then, we add RedirectAnonymousSubscriber.php to mymodule/src/EventSubscriber:


namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;

 * Event subscriber subscribing to KernelEvents::REQUEST.
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();

  public function checkAuthStatus(Event $event) {

    $allowed = [

    if ( ($this->account->isAnonymous()) && ( !in_array(\Drupal::routeMatch()->getRouteName(), $allowed)) ) {

      // add logic to check other routes you want available to anonymous users,
      // otherwise, redirect to login page.
      $route_name = \Drupal::routeMatch()->getRouteName();
      if (strpos($route_name, 'view') === 0 && strpos($route_name, 'rest_') !== FALSE) {

      $response = new RedirectResponse('/user/login', 302);


  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkAuthStatus');
    return $events;