12

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
astletron
  • 1,387
  • 1
  • 14
  • 26

1 Answers1

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
Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
astletron
  • 1,387
  • 1
  • 14
  • 26