Pengesahan Pengguna Automatik Selepas Pendaftaran di Symfony
Setelah membuat akaun, adalah wajar untuk log masuk pengguna secara automatik daripada memerlukan mereka memberikan mereka tauliah lagi. Begini cara anda boleh mencapai ini dalam 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 } }
Anda perlu mengubah suai kod ini mengikut konfigurasi khusus projek anda. Dengan melaksanakan langkah-langkah ini, anda boleh memastikan bahawa pengguna disahkan secara automatik selepas menyelesaikan proses pendaftaran.
Atas ialah kandungan terperinci Bagaimana untuk Log Masuk Pengguna Secara Automatik Selepas Pendaftaran di Symfony?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!