src/EventListener/KeycloakLogoutListener.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Security\Dto\TokensBag;
  4. use App\Model\User;
  5. use App\Service\KeycloakApiService;
  6. use App\Specification\KeycloakModeUsed;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  13. use Symfony\Component\Security\Http\Event\LogoutEvent;
  14. class KeycloakLogoutListener implements EventSubscriberInterface
  15. {
  16.     private ParameterBagInterface $param;
  17.     private LoggerInterface $logger;
  18.     private KeycloakApiService $keycloakApiService;
  19.     private TokenStorageInterface $tokenStorage;
  20.     private UrlGeneratorInterface $urlGenerator;
  21.     private string|bool $vistoryRedirect;
  22.     private string $mcotPortailRedirect;
  23.     public function __construct(
  24.         UrlGeneratorInterface $urlGenerator,
  25.         TokenStorageInterface $tokenStorage,
  26.         KeycloakApiService $keycloakApiService,
  27.         LoggerInterface $logger,
  28.         ParameterBagInterface $param,
  29.     ) {
  30.         $this->urlGenerator $urlGenerator;
  31.         $this->tokenStorage $tokenStorage;
  32.         $this->keycloakApiService $keycloakApiService;
  33.         $this->logger $logger;
  34.         $this->param $param;
  35.         $this->vistoryRedirect $this->param->get('vistory_redirect');
  36.         $this->mcotPortailRedirect $this->param->get('mcot_portail_domain_name');
  37.     }
  38.     public function logoutFromOidcProvider(LogoutEvent $event): void
  39.     {
  40.         if (KeycloakModeUsed::isSatisfiedBy($this->param)) {
  41.             $token $this->tokenStorage->getToken();
  42.             $user $token->getUser();
  43.             if (!$user instanceof User) {
  44.                 return;
  45.             }
  46.             $tokens $token->getAttribute(TokensBag::class);
  47.             if (null === $tokens) {
  48.                 throw new \LogicException(sprintf('%s token attribute is empty'TokensBag::class));
  49.             }
  50.             $this->logger->info("***** Keycloak logout *****");
  51.             $this->keycloakApiService->logout($tokens->getRefreshToken());
  52.             $redirect $this->vistoryRedirect == 'true' $this->urlGenerator->generate('login') : $this->mcotPortailRedirect;
  53.             $event->setResponse(new RedirectResponse($redirect));
  54.         }
  55.     }
  56.     public static function getSubscribedEvents(): array
  57.     {
  58.         return [LogoutEvent::class => 'logoutFromOidcProvider'];
  59.     }
  60. }