Authentication 如何在Symfony 4上的功能测试中对用户进行身份验证
我正在测试一个用isgrated('ROLE_ADMIN')注释保护的页面。如何发出一个请求来模拟一个具有“role\u ADMIN”角色的授权用户?Authentication 如何在Symfony 4上的功能测试中对用户进行身份验证,authentication,functional-testing,symfony-4.3,Authentication,Functional Testing,Symfony 4.3,我正在测试一个用isgrated('ROLE_ADMIN')注释保护的页面。如何发出一个请求来模拟一个具有“role\u ADMIN”角色的授权用户? <?php namespace App\Tests\Controller; use Symfony\Component\BrowserKit\Cookie; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Security\Core
<?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);
}
}