A
A
Alexander2015-03-31 19:47:21
symfony
Alexander, 2015-03-31 19:47:21

How to make authorization on no more than one device in Symfony 2?

How to make authorization on only one device in Symfony 2? When a user logs in from one computer, they must be logged out on other computers. What is the best way to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-03-31
Protko @Fesor

symfony.com/doc/current/components/http_foundation...
Well, either remember the token issued during authorization and check if the token stored in the session matches the one you remember.

A
Alexander, 2015-06-15
@CooperIII

I'll answer my own question. Here is my solution.
Create the EventListener.php file

namespace project\UserBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;

class UserListener {

    protected $container;

    public function __construct($container = null) {
        if (!is_null($container)) {
            $this->container = $container;
        }
    }

    public function onAuthenticationSuccess() {
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $x = md5(rand(0, 1000));
        $user->setToken($x);
        $em = $this->container->get('doctrine')->getManager();
        $em->persist($user);
        $em->flush();
        $cookie = new Cookie('_token', $x, time() + 3600 * 24 * 7);
        $response = new Response();
        $response->headers->setCookie($cookie);
        $response->send();
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        if (!is_object($user)) {
            return;
        }
        $x = $user->getToken();
        $request = $this->container->get('request_stack')->getCurrentRequest();
        $cookies = $request->cookies->all();
        if (!isset($cookies['_token']) || $cookies['_token'] !== $x) {
            $this->container->get('request')->getSession()->invalidate();
            $this->container->get('security.context')->setToken(null);
            $event->setResponse($this->container->get('templating')->renderResponse('UserBundle:Login:login2.html.twig', array(), null));
        }
    }
}

At each entry, we write a unique token to the USER table and exactly the same token in cookies. And then in onKernelRequest() we check if the cookie matches the data from the table. If not, then a debugging occurs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question