当用户确认其注册(电子邮件中发送的链接(时,我可以像这样手动登录他(我不喜欢这段代码,但没有找到更好的方法来实现这一目标(:
$user = $em->find(...);
$securityToken = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($securityToken);
我的问题:我还需要设置记住我的cookie,但我不知道如何实现这一点。我试图弄清楚身份验证类在 Symfony 中是如何工作的,但它在那里是丛林:/
我知道Symfony生成一个密钥(存储在MySQL表中(,然后设置一个cookie,我应该用什么来重现相同的行为?
我没有使用任何类型的外部捆绑包,只是使用Symfony。
感谢任何帮助!
在一遍又一遍地阅读安全组件代码后,我找到了一种方法来记录用户并为他设置记住我的cookie。我不喜欢那种黑客,如果有人找到更清洁的方法,我很乐意测试它。我希望它可以帮助某人,我希望有一天我们能在symfony中看到一个手动登录助手。
// Replace "main" by the firewall name
$user = $em->find(...);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
// Find UsernamePasswordFormAuthenticationListener and call the onSuccess method
$authenticationListener = null;
foreach ($this->get('security.firewall.map.context.main')->getContext()[0] as $listener) {
if ($listener instanceof UsernamePasswordFormAuthenticationListener) {
$authenticationListener = $listener;
break;
}
}
if ($authenticationListener) {
// The onSuccess method is private
$onSuccessMethod = (new 'ReflectionClass($authenticationListener))->getMethod('onSuccess');
$onSuccessMethod->setAccessible(true);
$response = $onSuccessMethod->invoke($authenticationListener, $request, $securityToken);
// Do what you want with the response
}