Search code examples
phpsymfonysymfony-security

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

Solution

  • 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.