diff --git a/security/form_login_setup.rst b/security/form_login_setup.rst index 08763fbfc95..e18ce922aaa 100644 --- a/security/form_login_setup.rst +++ b/security/form_login_setup.rst @@ -373,4 +373,67 @@ 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, it is redirected to the login page. +At that point target path is set and after a successful login, the user will +be redirected to the target path set before. + +To set it on certain public routes, you can create an Event Subscriber: + +.. code-block:: php + 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; + + /** @var SessionInterface */ + private $session; + + public function __construct(SessionInterface $session) + { + $this->session = $session; + } + + /** + * Save targetPath for public routes + * + * @param GetResponseEvent $event + */ + public function onKernelRequest(GetResponseEvent $event): void + { + $request = $event->getRequest(); + + if (!$event->isMasterRequest()) { + return; + } + + if ($request->isXmlHttpRequest()) { + return; + } + + $includedRoutes = ['some-public-route', 'another-route']; + + if (!\in_array($request->attributes->get('_route'), $includedRoutes, true)) { + return; + } + + $this->saveTargetPath($this->session, 'main', $request->getUri()); + } + + public static function getSubscribedEvents() + { + return [ + KernelEvents::REQUEST => ['onKernelRequest'] + ]; + } + } + +This subscriber will save the target path for the *main* firewall for the `$includedRoutes`. If a user visits `some-public-route`, after a successful login, it will be redirected to that route. + .. _`MakerBundle`: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html