Symfony: Re-authenticate FOS user automatically without making users log back in

Integrating a WordPress user login with Symfony is pretty painless if you need to share user sessions.  Just don’t rely solely on that WordPress cookie, but cross reference a randomly assigned hash that can reference back to the WordPress user’s table.  When you get your system to authenticate a user and you find your FOS User Bundle session expired and forces the user to log back in, you can save them the trouble by “synchronizing” the WordPress user session by logging them in automatically in the FOS User Bundle like so:

$user=$userManager->findUserByEmail($userEmail);

if($user){
   $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
   $this->get('security.context')->setToken($token);
   $this->get('session')->set('_security_main',serialize($token));
}

Be sure to add this “use statement” up top in your controller/repo:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

 

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *