Search code examples
phpsymfony5

Symfony 5.3.9 manually logging out logged in user and log in in another user


I am using symfony 5.3.9, what I want to achieve is when I click on a button (vue 3 as front end), I call a function
like this:

public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher, SessionInterface $session, Security $security) {
    $this->tokenStorage = $tokenStorage;
    $this->eventDispatcher = $eventDispatcher;
    $this->session = $session;
    $this->security = $security;
}

public function token(Request $request): JsonResponse {
    $this->tokenStorage->setToken(null);
    $this->session->invalidate();
    $this->get('security.token_storage')->setToken(null);
    $user = $this->getUser();

    //show user by return or just var_dump
}

In the function token I am just trying to log out the user then the current user, $user should be null and it returns null, no problem there
the problem is if I call another end point and I return the user connected just after making the call for the token function, the old user still remains, for example

public function me(UserInterface $user = null): JsonResponse {
   $username = $user->getUsername();
   return $username;
}

$user itself should be null here and give me an error, but the user itself it still filled with the old useri

Please note that I have just put parts of the code here which i thought were appropriate so please forgive the "untidiness" of the code

I have tried

$this->tokenStorage->setToken(null);
$this->session->invalidate();
$this->get('security.token_storage')->setToken(null);

but the user never gets deleted.


Solution

  • I am using stateless firewall and JWT token and still trying to modify sessions... I'm just regenerating the jwt using the new user and sending it to the browser as part of -set-cookie header did the trick. And the cookie has to be cleared first through else i will not be updated it ifs not yet expired.