是的,您可以通过类似于以下内容的方式执行此操作:
use SymfonyComponentEventDispatcherEventDispatcher, SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken, SymfonyComponentSecurityHttpEventInteractiveLoginEvent;public function registerAction(){ // ... if ($this->get("request")->getMethod() == "POST") { // ... Do any password setting here etc $em->persist($user); $em->flush(); // Here, "public" is the name of the firewall in your security.yml $token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles()); // For older versions of Symfony, use security.context here $this->get("security.token_storage")->setToken($token); // Fire the login event // Logging the user in above the way we do it doesn't do this automatically $event = new InteractiveLoginEvent($request, $token); $this->get("event_dispatcher")->dispatch("security.interactive_login", $event); // maybe redirect out here }}当您在上下文中设置令牌时,最后不会自动触发事件,而通常在使用登录表单或类似方法时触发。因此,将其包含在此处的原因。您可能需要根据使用情况调整使用的令牌的类型-
UsernamePasswordToken上面显示的是核心令牌,但是如果需要,您可以使用其他令牌。
编辑 :调整了上面的代码以解释’public’参数,并根据下面的Franco的评论将用户的角色添加到令牌创建中。



