I have Drupal 8.5.1 and I am trying to force a redirect for anonymous users to the CAS login page. First I thought that the issue was related with the firing of the checkAuthStatus
function below, however, the issue seems related to an endless redirect:
namespace Drupal\my_custom_module\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) {
\Drupal::logger('my_custom_module')->error('THIS IS A TEST');
if ($this->account->isAnonymous()
&& \Drupal::routeMatch()->getRouteName() != 'cas.legacy_login'
&& \Drupal::routeMatch()->getRouteName() != 'cas.service') {
$response = new RedirectResponse('/cas', 301);
$response->send();
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['checkAuthStatus', 27];
return $events;
}
}
What could be the issue?
$event->setResponse($response);
logger
calls and they are only executed when the visited URL is an internal page. On the front page is not being executed. So that means theRedirectResponse
object is only created on internal pages, so using theCacheableRedirectResponse
will not make any difference.drush cr
multiple times to clear the cache, but the issue continues.