使用FOSUserBundle自动登录Symfony2

使用FOSUserBundle自动登录Symfony2,symfony,authentication,authorization,fosuserbundle,Symfony,Authentication,Authorization,Fosuserbundle,我在我的Symfony2应用程序(使用FOSUserBundle)中创建了一个单独的注册机制,该机制存在于常规注册之外 在我创建并将用户持久化到数据库之后,是否有任何方法可以自动登录当前用户。之后,用户将被重定向到需要登录用户的页面(由于自动登录,用户可以访问该页面) 这基本上是我创建用户的方法: public function signupAction(Request $request) { $user = new User(); $form = $this->crea

我在我的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()
    ));
}
注意:这似乎不再适用于Symfony3

引用自a至a:


它在Symfony 3中不起作用。1@AlexeyKosov,在Symfony 3.1中为我工作,使用了
安全性。令牌存储
而不是
安全性。上下文
FOSUserBundle有一个更简单、更干净的解决方案:
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));