在 Symfony 中注册后自动进行用户身份验证
创建帐户后,最好自动登录用户,而不是要求他们提供自己的信息再次凭证。以下是如何在 Symfony 中实现此目的:
Symfony 4.0
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use YourNamespace\UserBundle\Entity\User; class LoginController extends AbstractController { public function registerAction() { $user = //Handle getting or creating the user entity likely with a posted form $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->container->get('security.token_storage')->setToken($token); $this->container->get('session')->set('_security_main', serialize($token)); //The user is now logged in, you can redirect or do whatever. } }
Symfony 2.6.x - Symfony 3.0.x
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use YourNamespace\UserBundle\Entity\User; class LoginController extends Controller { public function registerAction() { $user = //Handle getting or creating the user entity likely with a posted form $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get('security.token_storage')->setToken($token); $this->get('session')->set('_security_main', serialize($token)); } }
Symfony 2.3.x
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use YourNamespace\UserBundle\Entity\User; class LoginController extends Controller { public function registerAction() { $user = //Handle getting or creating the user entity likely with a posted form $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get('security.context')->setToken($token); $this->get('session')->set('_security_main', serialize($token)); //Now you can redirect where ever you need and the user will be logged in } }
您需要根据项目的具体配置修改此代码。通过实施这些步骤,您可以确保用户在完成注册过程后自动进行身份验证。
以上是Symfony 注册后如何自动登录用户?的详细内容。更多信息请关注PHP中文网其他相关文章!