For Symfony 5, you can use out of the box functionalities to create login and registration forms.
Using Symfony\Component\Security\Guard\GuardAuthenticatorHandler is key point.
You can use GuardAuthenticatorHandler in registration controller after successful registration. It logs in user and redirects to page defined in onAuthenticationSuccess from LoginFormAuthenticator.
Below, I added some code snippets.
<?php
namespace App\Controller\Login;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class LoginController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}
<?php
namespace App\Security;
use App\Entity\User\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return 'app_login' === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email could not be found.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getPassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
// if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
// return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
// }
//
// // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
// throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate('app_login');
}
}
<?php
namespace App\Controller;
use App\Entity\User\User;
use App\Security\LoginFormAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
class RegistrationController extends AbstractController
{
private EntityManagerInterface $objectManager;
private UserPasswordEncoderInterface $passwordEncoder;
private GuardAuthenticatorHandler $guardHandler;
private LoginFormAuthenticator $authenticator;
/**
* RegistrationController constructor.
* @param EntityManagerInterface $objectManager
* @param UserPasswordEncoderInterface $passwordEncoder
* @param GuardAuthenticatorHandler $guardHandler
* @param LoginFormAuthenticator $authenticator
*/
public function __construct(
EntityManagerInterface $objectManager,
UserPasswordEncoderInterface $passwordEncoder,
GuardAuthenticatorHandler $guardHandler,
LoginFormAuthenticator $authenticator
) {
$this->objectManager = $objectManager;
$this->passwordEncoder = $passwordEncoder;
$this->guardHandler = $guardHandler;
$this->authenticator = $authenticator;
}
/**
* @Route("/registration")
*/
public function displayRegistrationPage()
{
return $this->render(
'registration/registration.html.twig',
);
}
/**
* @Route("/register", name="app_register")
*
* @param Request $request
* @return Response
*/
public function register(Request $request)
{
// if (!$this->isCsrfTokenValid('sth-special', $request->request->get('token'))) {
// return $this->render(
// 'registration/registration.html.twig',
// ['errorMessage' => 'Token is invalid']
// );
// }
$user = new User();
$user->setEmail($request->request->get('email'));
$user->setPassword(
$this->passwordEncoder->encodePassword(
$user,
$request->request->get('password')
)
);
$user->setRoles(['ROLE_USER']);
$this->objectManager->persist($user);
$this->objectManager->flush();
return $this->guardHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$this->authenticator,
'main' // firewall name in security.yaml
);
return $this->render('base.html.twig');
}
}