API request authorization using FOSOAuthBundle in UnitTests

I am trying to authorize a test user in my UnitTest cases. To do this, I create the following helper function for the tests (this is not very convenient, but I can do it better after that):

public function generateOAuthLoginData(EntityManager $em, Client $client) {
  $apiclient = new \OAuthBundle\Entity\Client();
  $apiclient->setRandomId('randomid');
  $apiclient->setSecret('secret');
  $apiclient->setAllowedGrantTypes(['password', 'refresh_token']);
  $em->persist($apiclient);

  $user = new \AppBundle\Entity\User();
  $user->setEmail('user@test.de');
  $user->setUsername('user');
  $user->setPlainPassword('password');
  $user->setFirstname('User');
  $user->setLastname('Test');
  $user->addRole('ROLE_ADMIN');
  $em->persist($user);

  $em->flush();

  $crawler = $client->request('GET', '/oauth/v2/token?client_id=1_randomid&client_secret=secret&grant_type=password&username=user@test.de&password=password');
  $access_token = json_decode($client->getResponse()->getContent())->access_token;

  return ['ACCEPT' => 'application/json', 'AUTHORIZATION' => 'Bearer '.$access_token];
}

      

I am getting an access token (tested it in code and in the database) and now I am trying to make some API requests by doing

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

      

in the test class.

I tried with RESTer (Firefox plugin for making custom requests) and it works there. But in tests I get a 401 error. Here is the error from the log file:

[2017-04-18 13:45:32] security.INFO: An AuthenticationException was thrown; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AuthenticationCredentialsNotFoundException(code: 0): A Token was not found in the TokenStorage. at /var/www/testproject/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php:53)"} []
[2017-04-18 13:45:32] security.DEBUG: Calling Authentication entry point. [] []

      

What is my fault? And why does it work in RESTer and not UnitTests?

+3


source to share





All Articles