Let’s say your website uses Symfony’s “Friends of Symfony” FOS User Bundle but you also have different internal systems and other ways users can authenticate.  You don’t want to keep pestering the user to log back in, the better solution is to get your authentication system that’s outside the FOS User Bundle to talk to it.

You take extra security precautions, perhaps white list their IP and use some other encrypted cookies values.  Here’s one way you can “refresh” their login if you send the user back to a Symfony controller that falls under the FOS User Bundle’s firewall, which you’ve defined in your Symfony’s security.yml settings file.

So if you can extract the user’s email address from the cookies already set, hopefully through encrypted means, of course, you can essentially log them back in automatically by defining the $user as the object you actually get from the userManager object.

$userManager = $this->container->get('fos_user.user_manager');
$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 at the top of the controller the use of the the object:  use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

Learn more from Symfony’s documentation about Authentication.  The above is only one solution, I found the FOS User Bundle is pretty simple and flexible to work with.

Are you looking for experienced PHP, Symfony, WordPress, MySQL, LAMP, or Magento developers?  Perhaps you are looking to modernize your company’s systems, considering going open source, or launching a new e-commerce site?  Contact us and we can connect you to a network of flexible web developer freelancers that matches your organization’s needs and budget.


Here is a quick way to access the user object from the Symfony user or the FOSUserBundle.  In this Twig example below is a conditional statement that if the user is authenticated and has a role, it will display “Hi Aaron Belchamber” or whatever the user’s name is.

{% if is_granted("ROLE") %}

    Hi {{ app.user.username }}!

{% endif %}