How to log in User in Session within a Functional Test in Symfony 2.3?

心不动则不痛 提交于 2019-12-03 16:03:20

Finaly i solve it! This is example of working code:

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

class ProfileControllerTest extends WebTestCase
{
    protected function createAuthorizedClient()
    {
        $client = static::createClient();
        $container = static::$kernel->getContainer();
        $session = $container->get('session');
        $person = self::$kernel->getContainer()->get('doctrine')->getRepository('FoxPersonBundle:Person')->findOneByUsername('master');

        $token = new UsernamePasswordToken($person, null, 'main', $person->getRoles());
        $session->set('_security_main', serialize($token));
        $session->save();

        $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

        return $client;
    }

    public function testView()
    {
        $client = $this->createAuthorizedClient();
        $crawler = $client->request('GET', '/person/view');
        $this->assertEquals(
            200,
            $client->getResponse()->getStatusCode()
        );
    }   

Hope it helps to save your time and nerves ;)

As an addition to the accepted solution I will show my function to login user in controller.

// <!-- Symfony 2.4 --> //

use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

private function loginUser(UsernamePasswordToken $token, Request $request)     {
    $this->get('security.context')->setToken($token);

    $s = $this->get('session');
    $s->set('_security_main', serialize($token)); // `main` is firewall name
    $s->save();

    $ed = $this->get('event_dispatcher');

    $ed->dispatch(
        AuthenticationEvents::AUTHENTICATION_SUCCESS,
        new AuthenticationEvent($token)
    );

    $ed->dispatch(
        "security.interactive_login",
        new InteractiveLoginEvent($request, $token)
    );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!