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:
services: redirect_anonymous.event_subscriber: class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber arguments: [] tags: - {name: event_subscriber}
Then, we add RedirectAnonymousSubscriber.php to mymodule/src/EventSubscriber:
<?php 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 = [ 'user.logout', 'user.register', 'user.login', 'user.reset', 'user.reset.form', 'user.reset.login', 'user.login.http', 'user.logout.http', 'user.pass' ]; 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) { return; } $response = new RedirectResponse('/user/login', 302); $response->send(); } } public static function getSubscribedEvents() { $events[KernelEvents::REQUEST][] = array('checkAuthStatus'); return $events; } }