Get ride of curious users on headless Drupal

By yuseferi, 16 December, 2016
Get ride of curious users on headless Drupal

We using Drupal 8 as headless ( Decoupled) core of  Zeyton project,we  setup Drupal at core.zeyton.com and that provides data for our Front-end Layer, One of our requirements is only admin could access the Drupal pages, I mean anonymous user couldn't surf Drupal pages So I suggest a plan to satisfy this requirement, my scenario  is when user try to access Drupals pages  we check user if  user is not logged on or current path is not our ENDPOINTS paths redirect user to  login page, In Drupal 7 we could handle that with hook_init but hook_init is removed form Drupal 8 so we looking for Drupal equivalents  of hook_init , finally Handle it with our custom EventSubscriber

First create a custom module on  `modules/custom` ( we set it's name to "anonymousredirect" ) ,

 

Create anonymousredirect  directory at modules/custom

anonymousredirect.info.yml
 

name: 'Anonymous Redirect'
type: module
description: 'Redirect Anonomus user to login page and prevent access to any pages'
core: 8.x
package: Contributes
version: 1.x


anonymousredirect.services.yml

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

Create  RedirectAnonymousSubscriber.php at `anonymousredirect/src/EventSubscriber/` with following contents

 

<?php
namespace Drupal\zeytondev\EventSubscriber;

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

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

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

    public function checkAuthStatus(GetResponseEvent $event) {

        if ($this->account->isAnonymous() && \Drupal::routeMatch()->getRouteName() != 'user.login') {
            // 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', 301);
        $event->setResponse($response);
        $event->stopPropagation();
        }
    }

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

}

and just go `admin/modules` and find **Anonymous Redirect** and enable it, congratulations now you block curious users to surf your pages in a headless application. you can cone this module on my github .

Additional Useful Resources :

https://drupalize.me/blog/201502/responding-events-drupal-8

https://www.chapterthree.com/blog/how-to-register-event-subscriber-drupal8