DmitryR DmitryR - 9 months ago 37
PHP Question

Symfony 2 functional test: authenticate user of own User class

As described in answer of How to use an authenticated user in a Symfony2 functional test? there is a simple solution with


But I have different User class (some necessary additional fields) and I want to authenticate user with it.

How can I setup providders for it?


This is a tricky issue discussed here: Though 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());

$session = $client->getContainer()->get('session');
$session->set('_security_' . 'main_firewall', serialize($token));

$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;