Search code examples
phpauthenticationsymfony4event-listener

How to avoid multiple user sessions in symfony 4?


How can I prevent a register user from accessing the site from multiple devices?

I create a function onSecurityInteractiveLogin in a EventListener

<?php


namespace App\EventListener;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class LoginListener
{

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();
        $session = $event->getRequest()->getSession();
        //TODO validate if that user is logged in
    }


}

But I can't get if the user is logged in other device and close that session, I found a solution but in Symfony 2.3 in here.

Can anybody explain me a solution in Symfony 4?


Solution

  • The short answer is that you can't.

    The longer answer is more complex: there's no way for your site to know which devices belong to an anonymous user; from the point of view of the server, all the requests look like they are coming from random places (which they are).

    However, once the user has logged in, you can enforce more restrictions. The trick lies in how you issue authentication tokens and how to associate them with a user record in your application. There are a lot of ways to skin that cat, but they all involve keeping track of how many authentications have been granted to a user's account. Usually authentication requests get tracked with the user's IP and the user agent string from their browser to help distinguish one of the user's logins from another. E.g. when you log into GMail, you can view all the logins that have accessed the account -- that could help you identify a fraudulent login, but it also shows you how many devices (or browsers) have been used to log in.