Automatically login in Symfony2 with FOSUserBundle

authentication, authorization, fosuserbundle, symfony

Solution

Attention: This doesn't seem to work in Symfony3 anymore.

Quoting from the answer to a duplicate question:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

$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));

Problem

I have created an individual sign up mechanism in my Symfony2 app (using FOSUserBundle) which exists in addition to the regular registration. Is there any way - after I have created and persisted the User to the database - to automatically login that current user. And after that the User shall be redirected to a page which requires a logged in user (and due to the automatical login, the User can access that page)? This is basically my method to create the user: ``` public function signupAction(Request $request) { $user = new User(); $form = $this->createFormBuilder($user) ->...() ->getForm(); $form->handleRequest($request); if ($form->isValid()) { // Enable User $user->setEnabled(true); // Persist to DB $em->persist($user); $em->flush(); // Here I need the auto-login before redirecting to _root return $this->redirect($this->generateUrl('_root')); } return $this->render('MyBundle:MyController:signup.html.twig', array( 'form' => $form->createView() )); } ```

Original source

Related problems