在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>
Symfony 2.6.x - Symfony 3.0.xuse 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中文網其他相關文章!