Skip to content

[Security] Customize generated Login Link #15163

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
Apr 21, 2021
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
48 changes: 48 additions & 0 deletions security/login_link.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

// ...
}