How to authenticate a user programmatically

I have a controller that needs to add a user through a simple form, but I cannot force the user to be authenticated manually.

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken public function addAction($user) { $token =new UsernamePasswordToken( $user->getUsername(), $user->getPassword(), 'secured_area', $user->getRoles() ); $this->get('security.context')->setToken($token); // as suggested in some other answers $request->getSession()->set('_security_secured_area', serialize($token)); // as suggested in http://techblog.zabuchy.net/2012/manually-authenticate-symfony-2-user/ return $this->redirect($this->generateUrl('acme_project_secure_show' ) ); } } 

Redirecting to a safe route works, but then the $this->getUser() method returns null since authentication is not set properly ... I can get the user from $user= $this->get('security.context')->getToken(); instead of $user= $this->get('security.context')->getToken()->getUser(); shortcut for $this->getUser() see book here Any idea why?

+4
source share
3 answers

The problem is solved: there were no two points: 1) it was necessary to send InteractiveLoginEvent -thanks mpm for the link 2), the route of this controller was not under the secured_area firewall - merci Florian;)

+6
source

You can try this

 use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken $token = new UsernamePasswordToken($user, $user->getPassword(), "firewallname", $user->getRoles()); 
+1
source

As @ user19340357 says, you can initiate the token manually.

He forgot to say that you should install it in a security context:

 use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken $token = new UsernamePasswordToken($user, $user->getPassword(), "firewallname", $user->getRoles()); $securityContext = $this->container->get('security.context'); // do it your way $securityContext->setToken($token); 
-1
source

All Articles