以编程方式登录+记住我

时间:2016-02-03 20:22:55

标签: php symfony

当用户确认其注册(通过电子邮件发送的链接)时,我可以像这样手动记录他(我不喜欢这段代码,但是没有找到更好的方法来实现这一点) :

$user = $em->find(...);
$securityToken = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($securityToken);

我的问题:我还需要设置记住我的cookie ,但我不知道如何实现这一点。我试图弄清楚身份验证类在Symfony中是如何工作的,但是它的丛林在那里:/

我知道Symfony生成一个密钥(存储在MySQL表中),然后设置一个cookie,我应该用什么来重现相同的行为?

我没有使用任何类型的外部捆绑,只是Symfony。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在反复阅读安全组件代码之后,我找到了一种记录用户并为他设置记住我的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
}