在UnitTests中使用FOSOAuthBundle授权API请求

时间:2017-04-18 14:19:10

标签: symfony unit-testing oauth fosrestbundle

我尝试在UnitTest案例中授权测试用户。为此,我为测试创建了以下辅助函数(这不是很方便,但我之后可以做得更好):

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];
}

我得到一个访问令牌(在代码和数据库中检查它),现在我尝试通过执行来发出一些API请求

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

在测试课程中。

我尝试使用RESTer(一个用于制作自定义请求的Firefox插件)并在那里工作。但在测试中我得到401错误。以下是日志文件中的错误:

[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. [] []

我的错是什么?为什么它在RESTer中工作而不在UnitTests中工作?

1 个答案:

答案 0 :(得分:1)

您是否尝试使用 HTTP_Authorization 代替 AUTHORIZATION 作为数组键?