I try to authorize a test user in my UnitTest cases. For this I create for the tests the following helper function (that is not very handy, but I can make this better afterwards):
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 get a access token (checked it in the code and in the database) and now I try to make some API requests by executing
$crawler = self::$client->request('GET', '/api/users', [], [], self::$authorisationHeaders);
$this->assertEquals(200, self::$client->getResponse()->getStatusCode());
in the test class.
I tried with RESTer (a Firefox plugin to make custom requests) and there it works. But in the tests I get a 401 error. Here is the error out of 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's my fault? And why does it work in RESTer and not in the UnitTests?
Did you tried to use HTTP_Authorization instead of AUTHORIZATION as an array key?