如何在Symfony 4的功能测试中对用户进行身份验证

时间:2019-09-24 12:48:23

标签: authentication functional-testing symfony-4.3

我正在测试受IsGranted('ROLE_ADMIN')注释保护的页面。如何发出模拟角色为'ROLE_ADMIN'的已认证用户的请求?

1 个答案:

答案 0 :(得分:0)

我使用了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);
    }
}