Sorry, you need to enable JavaScript to visit this website.

How to redirect anonymous users to login page?

Submitted by abhaisasidharan on Fri, 09/03/2021 - 10:10

All you have to do is intercept every request, check if it is authenticated user and if not redirect to login page. There is an Event that is fired on every request, we need to subscribe to that event.
 

<?php

namespace Drupal\custom_module\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

/**
 * Class LoginEventSubscriber.
 */
class LoginEventSubscriber implements EventSubscriberInterface {

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a new LoginEventSubscriber object.
   */
  public function __construct(AccountProxyInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events['kernel.request'] = ['kernelRequest', -1000];

    return $events;
  }

  /**
   * This method is called when the kernel.request is dispatched.
   *
   * @param \Symfony\Component\EventDispatcher\Event $event
   *   The dispatched event.
   */
  public function kernelRequest(GetResponseEvent $event) {
    if ($this->currentUser->isAnonymous() && $event->getRequest()->getRequestUri() != '/user/login') {
      $response = new RedirectResponse('user/login', 302);
      $event->setResponse($response);
      $event->stopPropagation();
    }
  }

}

 

Add this to custom_module.services.yml file:

custom_module.login_listener:
    class: Drupal\custom_module\EventSubscriber\LoginEventSubscriber
    arguments: ['@current_user']
    tags:
      - { name: event_subscriber }