Symfony 2 functional test: authenticate user of own User class Symfony 2 functional test: authenticate user of own User class symfony symfony

Symfony 2 functional test: authenticate user of own User class


This is a tricky issue discussed here: https://github.com/symfony/symfony/issues/5228Though it is 2.1, it still happen to me using 2.2.

Here is how I do the test authentication:

// Create a new client to browse the application$client = static::createClient();$client->getCookieJar()->set(new Cookie(session_name(), true));// dummy call to bypass the hasPreviousSession check$crawler = $client->request('GET', '/');$em = $client->getContainer()->get('doctrine')->getEntityManager();$user = $em->getRepository('MyOwnBundle:User')->findOneByUsername('username');$token = new UsernamePasswordToken($user, $user->getPassword(), 'main_firewall', $user->getRoles());self::$kernel->getContainer()->get('security.context')->setToken($token);$session = $client->getContainer()->get('session');$session->set('_security_' . 'main_firewall', serialize($token));$session->save();$crawler = $client->request('GET', '/login/required/page/');$this->assertTrue(200 === $client->getResponse()->getStatusCode());// perform tests in the /login/required/page here..

Oh, and the use statements:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;use Symfony\Bundle\FrameworkBundle\Client;use Symfony\Component\BrowserKit\Cookie;


are u using a form login ? or http security?

when using the form login what i do in my tests is i just simulate a user logging in via the login form ...

    /**     * test of superuser ingelogd geraakt     */    public function testSuperAdminLogin()    {        $crawler = $this->client->request('GET', '/login');        $form = $crawler->selectButton('Sign In')->form();        $user = $this->em->getRepository('NonoAcademyBundle:User')            ->findOneByUsername('superadmin');        $crawler = $this->client            ->submit($form,                array('_username' => $user->getUsername(),                        '_password' => $user->getPassword()));        $this->assertTrue($this->client->getResponse()->isSuccessful());        $this            ->assertRegExp('/\/admin\/notifications/',                $this->client->getResponse()->getContent());    }

then just use that client and crawler, as they will act as the logged in user.Hope this helps you


You might also find these helpful especially if you are using a form login

private function doLogin(){    $this->client = static::createClient();    $username = 'your-username';    $password = 'your-password';    $crawler = $this->client->request('GET', '/login');    $form = $crawler->filter('your-submit-button-classname')->form();    $crawler = $this->client        ->submit($form,            array(                '_username' => $username,                '_password' => $password,            )       );}