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

4 thoughts on “Functional testing with authentication and Symfony 2.3, FOSUserBundle

  1. Great code!!
    The only more I needed to put in my code was:

    use Symfony\Component\BrowserKit\Cookie;

    Thanks you a lot!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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