注册后自动进行用户身份验证
在构建 Symfony 2 业务应用程序的过程中,经常会遇到自动用户身份验证的需求注册后。以下是实现此目标的方法:
Symfony 4.0 及更高版本
自动身份验证的方法与早期版本的 Symfony 保持不变。下面是一个使用 AbstractController 的示例:
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
在这些版本中,为了安全起见,不推荐使用 security.context。令牌_存储。这是更新后的控制器:
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 } }
请记住使用带有以下参数的 UsernamePasswordToken:用户实体、用户凭证(可选)、防火墙名称、用户角色。
以上是Symfony中如何实现注册后自动进行用户认证?的详细内容。更多信息请关注PHP中文网其他相关文章!