2014-01-30 210 views
2

我在我的Symfony2應用程序(使用FOSUserBundle)中創建了一個單獨的註冊機制,它除了定期註冊外還存在。用FOSUserBundle自動登錄Symfony2

有沒有什麼辦法 - 在我創建並保存用戶到數據庫後 - 自動登錄當前用戶。之後,用戶將被重定向到需要登錄用戶的頁面(並且由於自動登錄,用戶可以訪問該頁面)?

這基本上是我的方法來創建用戶:

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() 
    )); 
} 

回答

6

注意:這似乎並不在Symfony3工作了。

answerduplicate 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)); 
+0

它不會在Symfony的工作3.1 –

+1

@AlexeyKosov,通過使用'security.token_storage',而不是'security.context在Symfony的3.1爲我工作' – nowiko

+0

FOSUserBundle有一個更簡單,更乾淨的解決方案:https://stackoverflow.com/a/44386575/592477 – Nico

相關問題