As per Cerad's comment, here is the full answer.
Below is only the part of the code related to the question & answer. These are not the full files.
Also, this is only for Symfony ^5.2 that is not using guard to authenticate the user.
/* config/packages/security.yaml */
security:
enable_authenticator_manager: true
firewalls:
main:
custom_authenticators:
- App\Security\SecurityAuthenticator
/* src/Security/SecurityAuthenticator.php */
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
/* automatically generated with the make:auth command,
the important part is to undestand that this is not a Guard implement
for the Authenticator class */
class SecurityAuthenticator extends AbstractLoginFormAuthenticator
{
}
/* src/Controller/RegistrationController.php */
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Security\SecurityAuthenticator;
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\Http\Authentication\UserAuthenticatorInterface;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="app_register")
*/
public function register(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,
UserAuthenticatorInterface $authenticator,
SecurityAuthenticator $formAuthenticator): Response
{
/* Automatically generated by make:registration-form, but some changes are
needed, like the auto-wiring of the UserAuthenticatorInterface and
SecurityAuthenticator */
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword($passwordEncoder->encodePassword($user, $form->get('password')->getData()));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// substitute the previous line (redirect response) with this one.
return $authenticator->authenticateUser(
$user,
$formAuthenticator,
$request);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
}