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 SymfonyComponentBrowserKitCookie(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"方法中的SymfonyComponentSecurityHttpFirewallContextListener"文件中.有这个代码:
it seems that the problem lies in the file "SymfonyComponentSecurityHttpFirewallContextListener" 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));
}
在我的情况下, if "$token instanceof AnonymousToken" 为真,因此会话密钥被删除.如果我注释掉该代码,一切都会按预期工作.
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屋!