Symfony 2.1中的功能测试中的身份验证 [英] Authentication in functional tests in Symfony 2.1
问题描述
我目前正在将2.0.*项目迁移到Symfony的当前2.1 beta.
I am currently in the process of migrating a 2.0.* project to the current 2.1 beta of Symfony.
在我的功能测试中,我目前拥有以下代码以创建具有身份验证的客户端:
In my functional tests i currently have this code to create a client with authentication:
$client = // create a normal test client
$role = 'ROLE_USER';
$firewallName = 'main';
$user = // pull a user from db
$client->getCookieJar()->set(new \Symfony\Component\BrowserKit\Cookie(session_name(), true));
$token = new UsernamePasswordToken($user, null, $firewallName, array($role));
self::$kernel->getContainer()->get('session')->set('_security_' . $firewallName,
serialize($token));
这在2.0.*中可以正常工作,但是在2.1中却不能,会话中的数据未设置.
this works as expected in 2.0.* but not in 2.1, the data does not get set in the session.
有什么想法吗?
编辑(添加更多信息):
问题似乎出在方法" onKernelResponse "中的文件" Symfony \ Component \ Security \ Http \ Firewall \ ContextListener "中.有以下代码:
it seems that the problem lies in the file "Symfony\Component\Security\Http\Firewall\ContextListener" in the method "onKernelResponse". There is this code:
if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) {
$session->remove('_security_'.$this->contextKey);
} else {
$session->set('_security_'.$this->contextKey, serialize($token));
}
在我的情况下,如果"$ token instanceof AnonymousToken"为true,并且因此删除了会话密钥.如果我注释掉该代码,一切都会按预期进行.
in my case the if "$token instanceof AnonymousToken" is true, and because of that the session key gets removed. if i comment out that code everything works as expected.
所以我想我的新问题是:我该怎么做才能使令牌不是匿名的?
So i guess my new question is: What can i do to make the token not anonymous?
推荐答案
验证用户身份的正确方法是:
Proper way to authenticate user is:
$firewallName = 'your-firewall-name';
$container = self::$kernel->getContainer()
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$container->get('security.context')->setToken($token);
和防火墙身份验证:
$session = $container->get('session');
$session->set('_security_'.$firewallName, serialize($token));
$session->save();
这篇关于Symfony 2.1中的功能测试中的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!