0

I created UnitTests for my Symfony app with the REST and OAuthBundle. To test the API behind the firewall, I create in my setUp method a UsernamePasswordToken by

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

Now I set the token by

self::$client->getContainer()->get('security.token_storage')->setToken($token);

Interestingly this token is only for one request in the storage. The first request with the first assertion succeeds, the second fails because of an 401 error. I checked the storage afterwards and the getToken() method returns NULL. If I set the token once more before the next request, this request succeeds also.

This is a sample request and the assertion:

$crawler = self::$client->request('GET', '/api/users');
$this->assertEquals(200, self::$client->getResponse()->getStatusCode());

So, I can set the token before each single request to solve the problem, but this would very annoying in all my tests. Why is the token after one "use" gone and how can I set a "lifetime" or something else?

mgluesenkamp
  • 529
  • 6
  • 19

1 Answers1

0

I think the problem is that each request the kernel and with it the container will load from the cache again where it does not contain your token. You have to persist your token in the session for it to stay permanently. How to do this is described in the documentation Testing HTTP Authentication

protected function login()
{
    $session = $this->client->getContainer()->get('session');
    // the firewall context defaults to the firewall name
    $firewallContext = 'secured_area';

    $token = new UsernamePasswordToken('admin', null, $firewallContext, array('ROLE_ADMIN'));
    $session->set('_security_'.$firewallContext, serialize($token));
    $session->save();

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

This should work over multiple requests and you can set it per test-method if you still want some tests not to be logged in.

dbrumann
  • 16,803
  • 2
  • 42
  • 58
  • This doesn't work for me. He create a session (checked it in filesystem) and the session object looks good, but now I get every time a 401 error. What can I do? – mgluesenkamp Apr 24 '17 at 09:41
  • Are you sure that your session is created with the authentication you provide or is it created before? Did you check whether your login is stored in the session data in your file? – dbrumann Apr 24 '17 at 11:18