註冊後自動進行用戶身份驗證
在構建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中文網其他相關文章!