Drupal 8: Redirect to page from Event Subscriber with destination query

drupal 8

Create your Event Subscriber

  1. Create your module's services yml file and declare the event subscriber
    services:
      mymodule.autologin:
        class: Drupal\mymodule\EventSubscriber\AutoLogin
        tags:
          - {name: event_subscriber}
    Save this as mymodule.services.yml inside mymodule folder
  2. Create the actual class used from above code
    <?php
    
    namespace Drupal\mymodule\EventSubscriber;
    
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class AutoLogin implements EventSubscriberInterface {
      public function redirectToLogin() {
         // PUT YOUR LOGIC HERE
      }
    
      /**
        * {@inheritdoc}
        */
      public static function getSubscribedEvents() {
        $events[KernelEvents::REQUEST][] = ['redirectToLogin'];
        return $events;
      }
    }
    Save this as AutoLogin.php inside mymodule/src/EventSubscriber folder
     

Redirect using URL::fromRoute with destination query

$current_path = \Drupal::service('path.current')->getPath();

$url = \Drupal\Core\Url::fromRoute('simplesamlphp_auth.saml_login', [], ['query' => ['destination' => $current_path, 'absolute' => TRUE]]);

$response = new RedirectResponse($url->toString(), 302);
$event->setResponse($response);

Put the above code in the AutoLogin::redirectLogin().

This code will get the current path and redirect to saml login page to auto login, then if the login is successful, it will redirect to the original path that we are trying to access.

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.