Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tobalsan/5e00ecded76aff67c3c1 to your computer and use it in GitHub Desktop.
Save tobalsan/5e00ecded76aff67c3c1 to your computer and use it in GitHub Desktop.

How to login a user programatically in Symfony2

First, insert use statement at the top of the file:

<?php

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

Then proceed to authenticate the user:

<?php

// create the authentication token
$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 event is important, it allows listeners to fire appropriate login actions

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