Functional testing with authentication and Symfony 2.3, FOSUserBundle

Running functional tests of Symfony 2.3 PHP applications where FOSUserBundle handles users is unfortunately easier said than done as far as user authentication is concerned. As I couldn’t find a working code example anywhere that showed how to authenticate a user before executing a functional test, I am publishing the code that I got to work in the end.

Simply put this function into your test class and call it to obtain a fully authenticated test client object.

protected function createAuthorizedClient()
{
 $client = static::createClient();
 $container = $client->getContainer();

 $session = $container->get('session');
 /** @var $userManager \FOS\UserBundle\Doctrine\UserManager */
 $userManager = $container->get('fos_user.user_manager');
 /** @var $loginManager \FOS\UserBundle\Security\LoginManager */
 $loginManager = $container->get('fos_user.security.login_manager');
 $firewallName = $container->getParameter('fos_user.firewall_name');

 $user = $userManager->findUserBy(array('username' => 'myusername'));
 $loginManager->loginUser($firewallName, $user);

 // save the login token into the session and put it in a cookie
 $container->get('session')->set('_security_' . $firewallName, 
 serialize($container->get('security.context')->getToken()));
 $container->get('session')->save();
 $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

 return $client;
}

Feel free to leave feedback.

Advertisements