Skip to content

Instantly share code, notes, and snippets.

@scodx
Last active August 29, 2015 14:24
Show Gist options
  • Save scodx/b0b6775a244f84613891 to your computer and use it in GitHub Desktop.
Save scodx/b0b6775a244f84613891 to your computer and use it in GitHub Desktop.

How to login a user programatically in Symfony2

http://hasin.me/2013/10/27/how-to-login-a-user-programatically-in-symfony2/

Sometime, you may need to log in an user manually from code, instead of generic form based log in. To do it, you need to use Two Security component “UsernamePasswordToken” and “InteractiveLoginEvent”. We will also use another exception object “UsernameNotFoundException” if the user is not found.

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

Now from your controller, you can login an user like this

$em = $this->getDoctrine();
$repo  = $em->getRepository("UserBundle:User"); //Entity Repository
$user = $repo->loadUserByUsername($username);
if (!$user) {
    throw new UsernameNotFoundException("User not found");
} else {
    $token = new UsernamePasswordToken($user, null, "your_firewall_name", $user->getRoles());
    $this->get("security.context")->setToken($token); //now the user is logged in
     
    //now dispatch the login event
    $request = $this->get("request");
    $event = new InteractiveLoginEvent($request, $token);
    $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
}

Dispatching the “security.interactive_login” is important, because then every listeners which are bound to this event will work appropriately. But the actual login happens when you call setToken(…). Also make sure that you pass the correct firewall name which you had defined in your security.yml.

You can also recall the logged in user any time using the following code

//anywhere
$user =  $this->get('security.context')->getToken()->getUser();
 
//or from a controller
$user = $this->getUser();

That’s it. Hope you will find it handy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment