我尝试在我的 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/