n How to redirect anonymous user in Drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

How to redirect anonymous user in Drupal 8 & 9

 

Create MODULENAME.info.yml file

name: Redirect Anonymous User
type: module
description: Redirect anonymous user to login page
package: Custom
core: 8.x

 

Create custom service like this:

services:
  redirect_anonymous_user.event_subscriber:
    class: Drupal\redirect_anonymous_user\EventSubscriber\RedirectAnonymousUser
    arguments: []
    tags:
      - {name: event_subscriber}

 

Create class RedirectAnonymousUser:



<?php

namespace Drupal\redirect_anonymous_user\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Url;


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

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

    public function checkAuthStatus(GetResponseEvent $event) {

        if ($this->account->isAnonymous() && \Drupal::service('path.current')->getPath() == '/node/add/article') {

            // 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?destination=/node/add/article', 301);
            $event->setResponse($response);
            $event->stopPropagation();
        }
    }

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

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook