Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

php - Authentication in functional tests in Symfony 2.1

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));

this works as expected in 2.0.* but not in 2.1, the data does not get set in the session.

Any ideas?

Edit (adding more info):

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));
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

and firewall authentication:

$session = $container->get('session');
$session->set('_security_'.$firewallName, serialize($token));
$session->save();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...