如何在Symfony 2.7中关闭用户的所有会话?

Seb*_*Car 3 php symfony symfony-2.7

用户更改密码后(在恢复密码操作中),我需要使与该用户连接的所有会话无效(他可能登录多个浏览器/设备).因此,在我使用新密码在数据库中保存用户之后,我需要关闭在该用户的不同浏览器/设备中可能处于活动状态的所有会话.我试过这个:

$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
Run Code Online (Sandbox Code Playgroud)

还尝试过:

$this->get('security.token_storage')->getToken()->setAuthenticated(false);
Run Code Online (Sandbox Code Playgroud)

这也是:

$this->get('security.token_storage')->setToken(null);
Run Code Online (Sandbox Code Playgroud)

提前致谢!

我已将此添加到我的User类:

class User implements UserInterface, EquatableInterface, \Serializable{
  // properties and other methods

  public function isEqualTo(UserInterface $user){
    if ($user->getPassword() !== $this->getPassword()){
        return false;
    }
    if ($user->getEmail() !== $this->getEmail()){
        return false;
    }
    if ($user->getRoles() !== $this->getRoles()){
        return false;
    }
    return true;
  }


  /** @see \Serializable::serialize() */
  public function serialize()
  {
    return serialize(array(
        $this->id,
        $this->email,
        $this->password,
        // see section on salt below
        // $this->salt,
    ));
  }

  /** @see \Serializable::unserialize() */
  public function unserialize($serialized)
  {
    list (
        $this->id,
        $this->email,
        $this->password,
        // see section on salt below
        // $this->salt
    ) = unserialize($serialized);
  }
}
Run Code Online (Sandbox Code Playgroud)

Fed*_*kun 6

您需要跟踪该用户打开的每个会话.由于他可能登录多个浏览器/设备,因此他可能会使用不同的会话.

一种简单的方法是将会话ID的引用与用户ID一起保存,以便您可以获得用户的所有sessid.

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.
         */
    }
}
Run Code Online (Sandbox Code Playgroud)

然后注册security.interactive_login每次用户登录时将触发的事件.然后,您可以注册该侦听器

<service id="app_bundle.security.login_listener" class="AppBundle\Security\LoginListener.php">
    <tag name="kernel.event_subscriber" />
</service> 
Run Code Online (Sandbox Code Playgroud)

之后,当您想要撤消用户的所有会话时,您需要做的就是检索该用户的所有会话ID,循环并使用

$session = new Session();
$session->setId($sessid);
$session->start();
$session->invalidate();
Run Code Online (Sandbox Code Playgroud)