From 830b1f366d979e06bb6572a6c02540239b355060 Mon Sep 17 00:00:00 2001 From: roromix <16560617+roromix@users.noreply.github.com> Date: Sun, 28 Mar 2021 13:28:32 +0200 Subject: [PATCH] [Security] Customize generated Login Link --- security/login_link.rst | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/security/login_link.rst b/security/login_link.rst index 4e1bfa2d3da..b4dc13444f0 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -739,3 +739,51 @@ Then, configure this service ID as the ``success_handler``: ], ], ]); + +Customize generated Login Link +------------------------------ + +.. versionadded:: 5.3 + + The possibility to customize the login link was introduced in Symfony 5.3. + +In some use cases it may be useful to customize the Login Link. In addition +to the ``UserInterface``, it is therefore possible to pass a ``Request`` to the ``createLoginLink`` +method. In this example, our route is localized with the user locale which may +be different from the current locale:: + + // src/Controller/SecurityController.php + namespace App\Controller; + + // ... + use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface; + + class SecurityController extends AbstractController + { + /** + * @Route("/login", name="login") + */ + public function requestLoginLink(LoginLinkHandlerInterface $loginLinkHandler, Request $request) + { + // check if login form is submitted + if ($request->isMethod('POST')) { + // ... load the user in some way + + // clone and customize Request + $userRequest = clone $request; + $userRequest->setLocale($user->getLocale() ?? $request->getDefaultLocale()); + + // create a login link for $user this returns an instance + // of LoginLinkDetails + $loginLinkDetails = $loginLinkHandler->createLoginLink($user, $userRequest); + $loginLink = $loginLinkDetails->getUrl(); + + // ... + } + + return $this->render('security/login.html.twig'); + } + + // ... + }