4

如何在 Symfony2 功能测试中使用经过身份验证的用户的回答中所述?有一个简单的解决方案Symfony\Component\Security\Core\User\User

但是我有不同的用户类(一些必要的附加字段),我想用它来验证用户。

如何为其设置提供程序?

4

4 回答 4

10

This is a tricky issue discussed here: https://github.com/symfony/symfony/issues/5228 Though it is 2.1, it still happen to me using 2.2.

Here is how I do the test authentication:

// Create a new client to browse the application
$client = static::createClient();
$client->getCookieJar()->set(new Cookie(session_name(), true));

// dummy call to bypass the hasPreviousSession check
$crawler = $client->request('GET', '/');

$em = $client->getContainer()->get('doctrine')->getEntityManager();
$user = $em->getRepository('MyOwnBundle:User')->findOneByUsername('username');

$token = new UsernamePasswordToken($user, $user->getPassword(), 'main_firewall', $user->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);

$session = $client->getContainer()->get('session');
$session->set('_security_' . 'main_firewall', serialize($token));
$session->save();

$crawler = $client->request('GET', '/login/required/page/');

$this->assertTrue(200 === $client->getResponse()->getStatusCode());

// perform tests in the /login/required/page here..

Oh, and the use statements:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\BrowserKit\Cookie;
于 2013-05-14T13:05:26.037 回答
1

你在使用表单登录吗?还是http安全?

当使用表单登录时,我在测试中所做的只是模拟用户通过登录表单登录......

    /**
     * test of superuser ingelogd geraakt
     */
    public function testSuperAdminLogin()
    {
        $crawler = $this->client->request('GET', '/login');
        $form = $crawler->selectButton('Sign In')->form();
        $user = $this->em->getRepository('NonoAcademyBundle:User')
            ->findOneByUsername('superadmin');
        $crawler = $this->client
            ->submit($form,
                array('_username' => $user->getUsername(),
                        '_password' => $user->getPassword()));

        $this->assertTrue($this->client->getResponse()->isSuccessful());

        $this
            ->assertRegExp('/\/admin\/notifications/',
                $this->client->getResponse()->getContent());
    }

然后只需使用该客户端和爬虫,因为它们将充当登录用户。希望这可以帮助你

于 2013-05-14T12:58:10.050 回答
1

您可能还会发现这些很有帮助,尤其是在您使用表单登录时

private function doLogin()
{
    $this->client = static::createClient();
    $username = 'your-username';
    $password = 'your-password';

    $crawler = $this->client->request('GET', '/login');
    $form = $crawler->filter('your-submit-button-classname')->form();

    $crawler = $this->client
        ->submit($form,
            array(
                '_username' => $username,
                '_password' => $password,
            )
       );
}
于 2016-09-06T12:29:06.233 回答
0

我找到了解决方案。

首先,我们必须创建新的用户提供者:如此FakeUserProvider所述。 它应该实施。
UserProviderInterface

loadUserByUsername应该创建必要的用户对象。

于 2013-05-14T19:41:42.457 回答