简体   繁体   中英

Symfony force login and remember me

Following code will force login user automatically and it works fine. I want to add remember me functionality. So when we force login user and then also add remember me , so next time he automatically login to the site.

// 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();

Use RemeberMeToken and there is no need to set it manually in session, just fire interactive_login event:

// 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)
);

EDIT: add this to your 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

If this will not work, try to add ?_remember_me=1 to the end of your check_path .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM