【问题标题】:Authorizing API requests using FOSOAuthBundle in UnitTests在单元测试中使用 FOS OAuth Bundle 授权 API 请求
【发布时间】:2017-04-18 14:19:10
【问题描述】:

我尝试在我的 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 中无效?

【问题讨论】:

    标签: symfony unit-testing oauth fosrestbundle


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2017-01-27
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多