php - 使用新的 Symfony 5 Authenticator 注册后如何手动验证用户?
问题描述
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:
- 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(),
]);
}
}
推荐阅读
- machine-learning - 当我们有 CountVectorizer 和 Tfidfvectorizer 时,NLP 中的 Tokenization 和 Lemmatization 的用例是什么
- python - 为什么最后一个端口号没有被附加到列表中?
- c# - EF Code First - 更改列最大长度而不最大化 DB
- sql - 使用日期为 2019-04-01 的时间函数使用 sqlite3 将时间增加 2 小时
- esb - 无法初始化启动控制器。找不到任务管理器
- sql - 如何从同一个月获取最大日期行?
- windows - Adobe Illustrator:在 Windows 中从 Extendscript 运行 python 文件
- github - 我的哪些存储库被 GitHub 归档在北极?
- typescript - 如何从 TypeScript 中的记录类型中提取 varargs 参数?
- django - 获取字段名称列表但无法访问对象中的值