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.
[sourcecode language=”php”]
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
[/sourcecode]
Now from your controller, you can login an user like this
[sourcecode language=”php”]
$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);
}
[/sourcecode]
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
[sourcecode language=”php”]
//anywhere
$user = $this->get(‘security.context’)->getToken()->getUser();
//or from a controller
$user = $this->getUser();
[/sourcecode]
That’s it. Hope you will find it handy 🙂