如何在Symfony2功能测试中模拟使用HWIOAuth进行身份验证?

12

HWIOAuthBundle是一个composer包,用于在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个回答

6
use Symfony\Component\BrowserKit\Cookie;

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');
        // Name of your firewall has to be prefixed by "_security_"
        $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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接