Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate authentication via HWIOAuth in a Symfony2 functional test?

HWIOAuthBundle is a composer bundle enabling social login in Symfony2 projects:

https://github.com/hwi/HWIOAuthBundle

The Symfony2 docs give an example of how to simulate authentication in a functional test:

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

I have not been successful in getting these two to work together in my tests, though. The Symfony2 security system indicates that there is a non-anonymous user but getUser() in my Controllers returns null.

Anyone had success with this or has some pointers on how to best debug or implement?

Using:

  • Symfony2 - 2.6.3
  • HWIOAuthBundle - dev-master - 309d802f8de9f39e30851a145a7fc0de69b94076
like image 654
astletron Avatar asked Jan 13 '15 16:01

astletron


1 Answers

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('[email protected]');
        $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
like image 193
astletron Avatar answered Oct 18 '22 11:10

astletron