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

$user =  $this->get('security.context')->getToken()->getUser();

//or from a controller
$user = $this->getUser();

That’s it. Hope you will find it handy :)

About these ads

2 thoughts on “How to login a user programatically in Symfony2”

  1. Good post,this is a pretty complex topic and many people need to do this kind of stuff. By the way, to login a user using something different than a login form, you should implement an authentication provider. The logic involved is quite the same you wrote, but you should put it in a SecurityListener rather than in a controller. There is a good cookbook for this and I wrote a post about this topic

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s