KeycloakRequestSubscriber.php in Keycloak OpenID Connect 8
File
src/EventSubscriber/KeycloakRequestSubscriber.php
View source
<?php
namespace Drupal\keycloak\EventSubscriber;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Drupal\keycloak\Service\KeycloakServiceInterface;
use Drupal\openid_connect\OpenIDConnectStateToken;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class KeycloakRequestSubscriber implements EventSubscriberInterface {
protected $keycloak;
protected $languageManager;
protected $pathProcessor;
protected $pathMatcher;
public function __construct(KeycloakServiceInterface $keycloak, LanguageManagerInterface $language_manager, InboundPathProcessorInterface $path_processor, PathMatcherInterface $path_matcher) {
$this->keycloak = $keycloak;
$this->languageManager = $language_manager;
$this->pathProcessor = $path_processor;
$this->pathMatcher = $path_matcher;
}
public function onKernelRequestCheckKeycloakRedirect(GetResponseEvent $event) {
if (!$this->keycloak
->isKeycloakSignOutEnabled()) {
return;
}
$request = clone $event
->getRequest();
if (!($request
->isMethod('GET') || $request
->isMethod('HEAD'))) {
return;
}
$path = $this->pathProcessor
->processInbound($request
->getPathInfo(), $request);
$language_none = $this->languageManager
->getLanguage(LanguageInterface::LANGCODE_NOT_APPLICABLE);
$pattern = Url::fromRoute('keycloak.logout', [], [
'language' => $language_none,
])
->toString();
if (!$this->pathMatcher
->matchPath($path, $pattern)) {
return;
}
parse_str($request
->getQueryString(), $request_query);
if (empty($request_query['id_token_hint'])) {
return;
}
$query = [
'state' => OpenIDConnectStateToken::create(),
] + $request_query;
if ($this->keycloak
->isI18nEnabled()) {
$langcode = $this->languageManager
->getCurrentLanguage()
->getId();
$languages = $this->keycloak
->getI18nMapping();
if (!empty($languages[$langcode])) {
$langcode = $languages[$langcode]['locale'];
}
$query['kc_locale'] = $langcode;
}
$sign_out_endpoint = Url::fromUri($this->keycloak
->getKeycloakSignOutEndpoint(), [
'query' => $query,
])
->toString(TRUE)
->getGeneratedUrl();
$response = new TrustedRedirectResponse($sign_out_endpoint, 302);
$event
->setResponse($response);
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'onKernelRequestCheckKeycloakRedirect',
35,
];
return $events;
}
}