在 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)); } }
Symfony 2.6.x - 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)); } }
以上是如何在 Symfony 应用程序中实现自动注册后登录?的详细内容。更多信息请关注PHP中文网其他相关文章!