function keycloak_page_attachments_alter in Keycloak OpenID Connect 8
Implements hook_page_attachments_alter().
Add our Keycloak session check to the page, if the user was logged in with Keycloak and SSO is enabled.
File
- ./
keycloak.module, line 249 - Hook implementations of the Keycloak module.
Code
function keycloak_page_attachments_alter(array &$build) {
/* @var $keycloak \Drupal\keycloak\Service\KeycloakServiceInterface */
$keycloak = \Drupal::service('keycloak.keycloak');
// Whether the current user is not a Keycloak user or check session
// is disabled.
if (!$keycloak
->isKeycloakUser() || !$keycloak
->isCheckSessionEnabled()) {
return;
}
$session_info = $keycloak
->getSessionInfo([
KeycloakServiceInterface::KEYCLOAK_SESSION_CLIENT_ID,
KeycloakServiceInterface::KEYCLOAK_SESSION_SESSION_ID,
]);
// Whether no session parameters were found.
if (empty($session_info[KeycloakServiceInterface::KEYCLOAK_SESSION_CLIENT_ID]) || empty($session_info[KeycloakServiceInterface::KEYCLOAK_SESSION_SESSION_ID])) {
return;
}
// Attach session check JS and session information to the page.
$build['#attached']['library'][] = 'keycloak/keycloak-session';
$build['#attached']['drupalSettings']['keycloak'] = [
'enableSessionCheck' => TRUE,
'sessionCheckInterval' => $keycloak
->getCheckSessionInterval(),
'sessionCheckIframeUrl' => $keycloak
->getCheckSessionIframeUrl(),
'logoutUrl' => Url::fromRoute('user.logout', [], [
'query' => [
'op_initiated' => 1,
],
'absolute' => TRUE,
])
->toString(),
'logout' => FALSE,
'clientId' => $session_info[KeycloakServiceInterface::KEYCLOAK_SESSION_CLIENT_ID],
'sessionId' => $session_info[KeycloakServiceInterface::KEYCLOAK_SESSION_SESSION_ID],
];
}