symfonylogoutsymfony6

Symfony 6.0 - Force logout user in controller


How can i force logout user logged from controle on the new Symfony 6 ? (Version 6.0.1)

I tried $tokenStorage->setToken($token); but setToken() need 2 args:

(public function setToken(string $tokenId, string $token);)

I tried $request->getSession()->invalidate(); but my user is always logged...

I want to logout the user and redirect to another route (à don't want redirect to logout route)

Thank you


I can't use /logout because i'm in a controller, and sometime I have to make sure no user is logged, because i do treatment when I'm comming to this route.

I need this:

When i go to /validate route:

My service:

<?php

namespace App\Service;

use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

class SecurityService
{

    public function forceLogout(
        Request $request,
        EventDispatcherInterface $eventDispatcher,
        TokenStorageInterface $tokenStorage) : void
    {
        $logoutEvent = new LogoutEvent($request, $tokenStorage->getToken());
        $eventDispatcher->dispatch($logoutEvent);
        $tokenStorage->setToken(null);
    }
}

This don't work, my $eventDispatcher->dispacth($logoutEvent) work only before i refresh my page, after i'm logged again !


Solution

  • I found soluce :

    public function forceLogout() : void
    {
        $logoutEvent = new LogoutEvent($this->requestStack->getCurrentRequest(), $this->tokenStorage->getToken());
        $this->eventDispatcher->dispatch($logoutEvent);
        $this->tokenStorage->setToken(null);
        $response = new Response();
        $response->headers->clearCookie('REMEMBERME');
        $response->send();
    }