How to close all sessions for a user in Symfony 2.7? How to close all sessions for a user in Symfony 2.7? symfony symfony

How to close all sessions for a user in Symfony 2.7?


You need to track every session open by that user. Since he may be logged on multiple browsers/devices, he may uses different sessions.

An easy way to do it is to save a reference of the session id together with the user id, so that you can get all the sessid of an user.

namespace AppBundle\Security;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;use Symfony\Component\Security\Http\SecurityEvents;class LoginListener implements EventSubscriberInterface{    public static function getSubscribedEvents()    {        return array(            SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',        );    }    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)    {        $user = $event->getAuthenticationToken()->getUser();        $session = $event->getRequest()->getSession();        /*         * Save $user->getId() and $session->getId() somewhere         * or update it if already exists.         */    }}

then register a security.interactive_login event that will be fired every time a user log in. You can then register the listener with

<service id="app_bundle.security.login_listener" class="AppBundle\Security\LoginListener.php">    <tag name="kernel.event_subscriber" /></service> 

After that, when you want revoke all the sessions for a user, all you need to do is retrieve all the session ids of that user, loop and destroy them with

$session = new Session();$session->setId($sessid);$session->start();$session->invalidate();


Sebcar,

That is a bug in the Symfony Security itself: Bug explanation to be reviewFirst Bug

So you will have to override the Abstract Token


According to documentation in default setup you it should already happen.

For example, if the username on the 2 User objects doesn't match for some reason, then the user will be logged out for security reasons. (...) Symfony also uses the username, salt, and password to verify that the User has not changed between requests

I don't know how your User is configured but you may need to implement EquatableInterface