From 6db6f82ae0b9cc47a32dd00b43eca821aca78015 Mon Sep 17 00:00:00 2001 From: Antoine Makdessi Date: Tue, 30 Jan 2024 08:35:33 +0100 Subject: [PATCH] [Security] SwitchUser: add dynamic redirection path --- src/Symfony/Component/Security/CHANGELOG.md | 5 +++++ .../Component/Security/Http/Firewall/SwitchUserListener.php | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Security/CHANGELOG.md b/src/Symfony/Component/Security/CHANGELOG.md index c80d2dde00f29..e03b8e9f2777d 100644 --- a/src/Symfony/Component/Security/CHANGELOG.md +++ b/src/Symfony/Component/Security/CHANGELOG.md @@ -3,6 +3,11 @@ CHANGELOG The CHANGELOG for version 5.4 and newer can be found in the security sub-packages (e.g. `Http/`). +7.1 +--- + +* Add a request query string `_redirect_path` handled in `SwitchUserListener` to control the redirection path post switch user. It takes precedence over the `SwitchUserListener $targetRoute` value if any. + 5.3 --- diff --git a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php index a8c7a652f6623..0bb24f76e9907 100644 --- a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php @@ -90,6 +90,7 @@ public function supports(Request $request): ?bool } $request->attributes->set('_switch_user_username', $username); + $request->attributes->set('_switch_user_redirect_path', $request->query->get('_redirect_path')); return true; } @@ -106,6 +107,9 @@ public function authenticate(RequestEvent $event): void $username = $request->attributes->get('_switch_user_username'); $request->attributes->remove('_switch_user_username'); + $redirectPath = $request->attributes->get('_switch_user_redirect_path'); + $request->attributes->remove('_switch_user_redirect_path'); + if (null === $this->tokenStorage->getToken()) { throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.'); } @@ -124,7 +128,7 @@ public function authenticate(RequestEvent $event): void if (!$this->stateless) { $request->query->remove($this->usernameParameter); $request->server->set('QUERY_STRING', http_build_query($request->query->all(), '', '&')); - $response = new RedirectResponse($this->urlGenerator && $this->targetRoute ? $this->urlGenerator->generate($this->targetRoute) : $request->getUri(), 302); + $response = new RedirectResponse((null !== $redirectPath) ? $redirectPath : ($this->urlGenerator && $this->targetRoute ? $this->urlGenerator->generate($this->targetRoute) : $request->getUri()), 302); $event->setResponse($response); }