Symfony 2功能测试:验证自己的User类的用户 [英] Symfony 2 functional test: authenticate user of own User class
问题描述
如如何在Symfony2功能测试中使用经过身份验证的用户?使用Symfony\Component\Security\Core\User\User
有一个简单的解决方案.
As described in answer of How to use an authenticated user in a Symfony2 functional test? there is a simple solution with Symfony\Component\Security\Core\User\User
.
但是我有不同的User类(一些必要的附加字段),我想用它对用户进行身份验证.
But I have different User class (some necessary additional fields) and I want to authenticate user with it.
如何设置供应商?
推荐答案
这是此处讨论的棘手问题: https://github.com/symfony/symfony/issues/5228 尽管它是2.1,但使用2.2仍然会发生在我身上.
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..
哦,还有use语句:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\BrowserKit\Cookie;
这篇关于Symfony 2功能测试:验证自己的User类的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!