symfony - 在单元测试中使用 FOS OAuth Bundle 授权 API 请求

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

我获得了一个访问 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 中无效?

最佳答案

您是否尝试使用 HTTP_Authorization 而不是 AUTHORIZATION 作为数组键?

关于symfony - 在单元测试中使用 FOS OAuth Bundle 授权 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474786/

相关文章:

java - 两条腿的 OAuth 和 Gmail Atom feed

symfony - 创建树嵌套选择选项

python - 是否可以阻止模块/全局类变量创建单元测试实例?

javascript - 如何使用 Jest 测试忽略导入语句?

c# - 存储和检索在使用 facebook 或 twitter 授权后为用户收到的 token

facebook - 带有 FB 连接的空白弹出窗口

symfony - 未指定范围-Google_Auth_Exception

symfony - 在 Symfony 2.1 抽象类型中访问当前用户

php - Twig:在循环内设置变量,在循环外使用它

c# - 测试类中的对象实例化