Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony functional test - controller method getUser returns null

I have method in in my functional test for user log in:

/**
 * @param User $user
 */
private function logIn(User $user)
{
    $firewallName = 'site';
    $session = $this->client->getContainer()->get('session');
    $securityContext = $this->client->getContainer()->get('security.context');

    $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));
    $securityContext->setToken($token);

    $session->set('_security_'.$firewallName, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);
}

When I try to get user in controller, then it returns null.

public function editProfile(Request $request)
{
    $user = $this->getUser(); //returns null
    ...
}

Is logIn method wrong?

Update

Test method:

public function testProfile() {
    ...
    $user = $this->createUser();
    $this->logIn($user);
    $this->client->request('POST', '/profile/edit', $data);
    ...
}
like image 811
Sergei Gorjunov Avatar asked Apr 07 '26 13:04

Sergei Gorjunov


1 Answers

Try change:

 $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));

to

 $token = new UsernamePasswordToken($user, null, $firewallName, array('ROLE_USER'));
like image 68
Evgeniy Kuzmin Avatar answered Apr 10 '26 02:04

Evgeniy Kuzmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!