使用FOSUserBundle自动登录Symfony2

Got*_*bel 2 authentication authorization symfony fosuserbundle

我在我的Symfony2应用程序中创建了一个单独的注册机制(使用FOSUserBundle),除了常规注册之外,它还存在.

有没有办法 - 在我创建并持久化用户到数据库之后 - 自动登录当前用户.之后,用户将被重定向到需要登录用户的页面(由于自动登录,用户可以访问该页面)?

这基本上是我创建用户的方法:

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()
    ));
}
Run Code Online (Sandbox Code Playgroud)

Got*_*bel 6

注意:这似乎不再适用于Symfony3.

从引用答案重复问题:

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));
Run Code Online (Sandbox Code Playgroud)