使用FOSUserBundle自动登录Symfony2

时间:2014-01-30 14:05:29

标签: symfony authentication authorization 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()
    ));
}

1 个答案:

答案 0 :(得分:6)

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

answer引用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));