Skip to content

Instantly share code, notes, and snippets.

@beberlei
Created September 17, 2011 12:14
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save beberlei/1223886 to your computer and use it in GitHub Desktop.
Easily Inject authenticated Symfony User into functional test
<?php
use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @group functional
*/
class MyWebTestCase extends WebTestCase
{
abstract protected function getCurrentUser();
/**
* @param string $firewallName
* @param array $options
* @param array $server
* @return Symfony\Component\BrowserKit\Client
*/
protected function createClientWithAuthentication($firewallName, array $options = array(), array $server = array())
{
/* @var $client \Symfony\Component\BrowserKit\Client */
$client = $this->createClient($options, $server);
// has to be set otherwise "hasPreviousSession" in Request returns false.
$client->getCookieJar()->set(new \Symfony\Component\BrowserKit\Cookie(session_name(), true));
/* @var $user UserInterface */
$user = $this->getCurrentUser();
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
self::$kernel->getContainer()->get('session')->set('_security_' . $firewallName, serialize($token));
return $client;
}
}
@alex88
Copy link

alex88 commented Sep 11, 2013

Will this work for multiple users? E.g. different clients each with an associated user?

@blafasel42
Copy link

Hi, is there something similar for current Symfony2 versions?

@blafasel42
Copy link

@cadot-info
Copy link

See http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html for updated version of this.

link it's possible <5.2

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