Skip to content

Commit 45f0ddb

Browse files
committed
Clarify target path functionality
1 parent 6724aca commit 45f0ddb

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

security/form_login_setup.rst

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,4 +423,49 @@ deal with this low level session variable. However, the
423423
:class:`Symfony\\Component\\Security\\Http\\Util\\TargetPathTrait` utility
424424
can 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

Comments
 (0)