这个问题在这里已经有了答案:
How to programmatically login/authenticate a user?
(5 个回答)
8年前关闭。
我有一个 Controller ,它应该通过一个简单的表单添加用户,但我无法手动验证用户。
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken
public function addAction($user)
{
$token =new UsernamePasswordToken(
$user->getUsername(),
$user->getPassword(),
'secured_area',
$user->getRoles()
);
$this->get('security.context')->setToken($token);
// as suggested in some other answers
$request->getSession()->set('_security_secured_area', serialize($token));
// as suggested in http://techblog.zabuchy.net/2012/manually-authenticate-symfony-2-user/
return $this->redirect($this->generateUrl('acme_project_secure_show' )
);
}
}
重定向到安全路由有效,但随后的方法
$this->getUser()
由于身份验证设置不正确,返回 null...我可以从
$user= $this->get('security.context')->getToken();
获取用户而不是 $user= $this->get('security.context')->getToken()->getUser();
$this->getUser()
的快捷方式看书here知道为什么吗?
最佳答案
问题已解决 - 缺少两点:1) 必须 dispatch InteractiveLoginEvent
- 感谢 mpm 提供链接 2) 该 Controller 的路由不在 secured_area
下防火墙 - 谢谢弗洛里安 ;)
关于symfony - 如何以编程方式对用户进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14512664/