Search code examples
sessionauthenticationsymfony-2.1csrffosuserbundle

symfony2/fos-user-bundle: Login User by Entity


I have a user entity in a symfony2 controller and i need to log that user in. Apparently i do not understand how the process works with the Csrf Token and loging in a user.

What do i have to do to log in the user?


Solution

  • Having an user object you can login/authenticate a user programmatically

        $token = new UsernamePasswordToken($user, $user->getPassword(),
                                           "public", $user->getRoles());
    
        $this->get("security.context")->setToken($token);
    
        // Trigger login event
        $event = new InteractiveLoginEvent($request, $token);
        $this->get("event_dispatcher")
             ->dispatch("security.interactive_login", $event);
    

    You need to have this classes included

    use Symfony\Component\EventDispatcher\EventDispatcher,
        Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken,
        Symfony\Component\Security\Http\Event\InteractiveLoginEvent;