如何在Symfony2功能测试中通过HWIOAuth模拟身份验证?

时间:2015-01-13 16:59:39

标签: php symfony testing hwioauthbundle

HWIOAuthBundle是一个在Symfony2项目中启用社交登录的作曲家包:

https://github.com/hwi/HWIOAuthBundle

Symfony2文档提供了如何在功能测试中模拟身份验证的示例:

http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html

但是,我没有成功地让这两个人在我的测试中一起工作。 Symfony2安全系统指示存在非匿名用户,但我的控制器中的getUser()返回null。

任何人都对此有所成功,或者对如何最好地调试或实施有一些指示?

使用:

  • Symfony2 - 2.6.3
  • HWIOAuthBundle - dev-master - 309d802f8de9f39e30851a145a7fc0de69b94076

1 个答案:

答案 0 :(得分:5)

use Liip\FunctionalTestBundle\Test\WebTestCase;
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser;

class ControllerTest extends WebTestCase
{
    public function testSecurity()
    {
        $client = static::createClient();
        $token = new OAuthToken('test', array( 'ROLE_USER', 'ROLE_OAUTH_USER' ));
        $user = new OAuthUser('test@test.com');
        $token->setUser($user);
        $session = $client->getContainer()->get('session');
        $session->set('_security_name_of_your_firewall', serialize($token));
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);

        // $client now acts as authenticated client