diff --git a/security/form_login_setup.rst b/security/form_login_setup.rst index 0d591cdb759..7c5001f7dba 100644 --- a/security/form_login_setup.rst +++ b/security/form_login_setup.rst @@ -423,4 +423,49 @@ deal with this low level session variable. However, the :class:`Symfony\\Component\\Security\\Http\\Util\\TargetPathTrait` utility can be used to read (like in the example above) or set this value manually. +When the user tries to access a restricted page, they are being redirected to +the login page. At that point target path will be set. After a successful login, +the user will be redirected to this previously set target path. + +If you also want to apply this behavior to public pages, you can create an +:doc:`event subscriber ` to set the target path manually +whenever the user browses a page:: + + namespace App\EventSubscriber; + + use Symfony\Component\EventDispatcher\EventSubscriberInterface; + use Symfony\Component\HttpFoundation\Session\SessionInterface; + use Symfony\Component\HttpKernel\Event\GetResponseEvent; + use Symfony\Component\HttpKernel\KernelEvents; + use Symfony\Component\Security\Http\Util\TargetPathTrait; + + class RequestSubscriber implements EventSubscriberInterface + { + use TargetPathTrait; + + private $session; + + public function __construct(SessionInterface $session) + { + $this->session = $session; + } + + public function onKernelRequest(GetResponseEvent $event): void + { + $request = $event->getRequest(); + if (!$event->isMasterRequest() || $request->isXmlHttpRequest()) { + return; + } + + $this->saveTargetPath($this->session, 'main', $request->getUri()); + } + + public static function getSubscribedEvents() + { + return [ + KernelEvents::REQUEST => ['onKernelRequest'] + ]; + } + } + .. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html