使用新的Symfony5Authenticator注册后如何手动验证用户?
Symfony的5已经改变了其防护装置的认证方法,以一个新的Passport基于一个,使用新的安全配置:enable_authenticator_manager: true;
我想知道如何在我的控制器中的注册表单方法中对用户进行身份验证,在 ORM(Doctrine)持久化用户之后;
我已成功使用登录表单对用户进行身份验证,但我仍然不知道如何手动执行此操作。
回答
根据Cerad的评论,这是完整的答案。
以下只是与问答相关的代码部分。这些不是完整的文件。
此外,这仅适用于不使用保护来验证用户的Symfony ^5.2 。
/* config/packages/security.yaml */
security:
enable_authenticator_manager: true
firewalls:
main:
custom_authenticators:
- AppSecuritySecurityAuthenticator
/* src/Security/SecurityAuthenticator.php */
use SymfonyComponentSecurityHttpAuthenticatorAbstractLoginFormAuthenticator;
/* 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 AppEntityUser;
use AppFormRegistrationFormType;
use AppSecuritySecurityAuthenticator;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use SymfonyComponentSecurityHttpAuthenticationUserAuthenticatorInterface;
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(),
]);
}
}
- Good answer. I was wondering how to get the user authenticator for the current firewall. Never occurred to me to just typehint against it. The user authenticator is actually a security bundle class which determines the current firewall based on the master request. Good stuff to know.
THE END
二维码