How to implement StackMiddleware for a redirection correctly?

I’m working on a redirection (for unauthenticated users) for my Drupal 8 site. Currently, the redirection works however, the redirection persists even after user is authenticated. I found this article piece helpful to point me in the right direction:

“Drupal 8 has two level cache, page cache and dynamic page cache. The issue you are having is more likely to intercept the page cache.
Add new class which implements ‘HttpKernelInterface’ and register ‘http_middleware’ with higher priority than 200 (280 will do).”

My problem is related to intercepting the page cache, so I am currently trying to implement the ‘HttpKernelInterface’ and register ‘http_middleware’ but unsuccessfully.
I created a custom module (example_module for example sake). My example_module.services.yml file:

services:
  example_module.event_subscriber:
    class: Drupalexample_moduleEventSubscriberRedirectAnonymousSubscriber
    tags:
      - { name: event_subscriber }
  example_module.stack_middleware:
    class: Drupalexample_moduleEventSubscriberStackMiddleware
    tags:
      - { name: http_middleware, priority: 210, responder: true }

Then in the same module I have a src/EventSubscriber/RedirectAnonymousSubscriber.php file like so:

<?php

namespace Drupalexample_moduleEventSubscriber;
namespace Drupalexample_moduleStackMiddleware;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentHttpKernelKernelEvents;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelHttpKernelInterface;


/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface,HttpKernelInterface {
  private $redirectCode = 301;

    /**
  * The wrapped HTTP kernel.
  *
  * @var SymfonyComponentHttpKernelHttpKernelInterface
  */
  protected $httpKernel;

  /**
  * Creates a HTTP middleware handler.
  *
  * @param SymfonyComponentHttpKernelHttpKernelInterface $kernel
  *   The HTTP kernel.
  */
  public function __construct(HttpKernelInterface $kernel) {
    $this->httpKernel = $kernel;
  }

  /**
  * {@inheritdoc}
  */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Only allow page caching on master request.
    if ($type === static::MASTER_REQUEST && $this->requestPolicy
      ->check($request) === RequestPolicyInterface::ALLOW) {
      $response = $this
        ->lookup($request, $type, $catch);
    } else {
      $response = $this
        ->pass($request, $type, $catch);
    }

    return $response;
  }

  public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = Drupal::currentUser()->isAuthenticated();
    $route_name = Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://google.com', $this->redirectCode);
      $response->send();
      exit(0);
    }
  }

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

Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching?
Do I have to create a separate custom module to implement my StackMiddleware class? How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache and have it run on every page(so it always checks to see if user is authenticated)? Any help appreciated. Thanks!

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

How to implement StackMiddleware for a redirection correctly?

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.