@@ -423,4 +423,49 @@ deal with this low level session variable. However, the
423423:class: `Symfony\\ Component\\ Security\\ Http\\ Util\\ TargetPathTrait ` utility
424424can be used to read (like in the example above) or set this value manually.
425425
426+ When the user tries to access a restricted page, they are being redirected to
427+ the login page. At that point target path will be set. After a successful login,
428+ the user will be redirected to this previously set target path.
429+
430+ If you also want to apply this behavior to public pages, you can create an
431+ :doc: `event subscriber </event_dispatcher >` to set the target path manually
432+ whenever the user browses a page::
433+
434+ namespace App\EventSubscriber;
435+
436+ use Symfony\Component\EventDispatcher\EventSubscriberInterface;
437+ use Symfony\Component\HttpFoundation\Session\SessionInterface;
438+ use Symfony\Component\HttpKernel\Event\GetResponseEvent;
439+ use Symfony\Component\HttpKernel\KernelEvents;
440+ use Symfony\Component\Security\Http\Util\TargetPathTrait;
441+
442+ class RequestSubscriber implements EventSubscriberInterface
443+ {
444+ use TargetPathTrait;
445+
446+ private $session;
447+
448+ public function __construct(SessionInterface $session)
449+ {
450+ $this->session = $session;
451+ }
452+
453+ public function onKernelRequest(GetResponseEvent $event): void
454+ {
455+ $request = $event->getRequest();
456+ if (!$event->isMasterRequest() || $request->isXmlHttpRequest()) {
457+ return;
458+ }
459+
460+ $this->saveTargetPath($this->session, 'main', $request->getUri());
461+ }
462+
463+ public static function getSubscribedEvents()
464+ {
465+ return [
466+ KernelEvents::REQUEST => ['onKernelRequest']
467+ ];
468+ }
469+ }
470+
426471.. _`MakerBundle` : https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html
0 commit comments