phpauthenticationsymfony4functional-testing

How do I authenticate user in functional test on Symfony 4?


I'm testing a page protected with IsGranted('ROLE_ADMIN') annotation. How do I make a request that simulate an autheticated user with role 'ROLE_ADMIN'?


Solution

  • I used this

    <?php
    
    namespace App\Tests\Controller;
    
    
    use Symfony\Component\BrowserKit\Cookie;
    use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
    use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
    
    /**
     * Test Page controller
     */
    class PageControllerTest extends WebTestCase
    {
    
        private $client = null;
    
        public function setUp()
        {
            $this->client = static::createClient();
        }
    
        public function testHomePage()
        {
            $client = static::createClient();
            $client->request('GET', '/');
            $this->assertTrue($client->getResponse()->isRedirect('/login'));
        }
    
        public function testHomePageSuccess()
        {
            $this->logIn();
            $this->client->request('GET', '/');
            $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        }
    
        private function logIn()
        {
            $session = $this->client->getContainer()->get('session');
            $firewallName = 'main';
            $firewallContext = 'main';
            $token = new UsernamePasswordToken('admin', null, $firewallName, ['ROLE_ADMIN']);
           $session->set('_security_'.$firewallContext, serialize($token));
           $session->save();
    
           $cookie = new Cookie($session->getName(), $session->getId());
           $this->client->getCookieJar()->set($cookie);
        }
    }