Skip to content

Clarify target path functionality #12380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 26, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions security/form_login_setup.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 </event_dispatcher>` 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