Symfony强制登录并记住我

时间:2016-07-21 09:42:45

标签: php symfony symfony-security

以下代码将自动强制登录用户,并且工作正常。我想添加记住我的功能。因此,当我们强制登录用户然后添加 记住我 时,下次他自动登录该网站。

// Auto Authenticate User
        $firewall = 'user_firewall';
        $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
        $this->get('security.token_storage')->setToken($token);

        $session = $this->get('session');
        $session->set('_security_'.$firewall, serialize($token));
        $session->save();

1 个答案:

答案 0 :(得分:1)

使用RemeberMeToken,无需在会话中手动设置,只需触发interactive_login事件:

// Auto Authenticate User
$firewall = 'user_firewall';
$key = $this->getParameter('secret'); //from parameters.yml
$token = new RememberMeToken($user, $firewall, $key);
$this->get('security.token_storage')->setToken($token);

$this->get('event_dispatcher')->dispatch(
    SecurityEvents::INTERACTIVE_LOGIN,
    new InteractiveLoginEvent($request, $token)
);

编辑: 将此添加到security.yml:

        yourProviderKey: # oauth i guess
            remember_me: true
        remember_me:
            secret:   '%secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
            #always_remember_me: true # optional

如果这不起作用,请尝试将?_remember_me=1添加到check_path的末尾。