You are here

function keycloak_openid_connect_post_authorize in Keycloak OpenID Connect 8

Implements hook_openid_connect_post_authorize().

Stores the Keycloak session_state parameter to the logged in user's session.

File

./keycloak.module, line 202
Hook implementations of the Keycloak module.

Code

function keycloak_openid_connect_post_authorize(UserInterface $account, array $context) {
  $tokens = isset($context['tokens']) ? $context['tokens'] : [];
  $plugin_id = isset($context['plugin_id']) ? $context['plugin_id'] : [];

  // Whether the client used for authentication was not keycloak.
  if (empty($plugin_id) || $plugin_id !== 'keycloak') {

    // Nothing to do. Bail out.
    return;
  }

  /* @var $keycloak \Drupal\keycloak\Service\KeycloakServiceInterface */
  $keycloak = \Drupal::service('keycloak.keycloak');

  // Decode user data from ID token. The hook does not provide the decoded
  // token information. So we create a new instance of the openid_connect
  // Keycloak plugin and use its decode method to decode the token again.
  // @see https://www.drupal.org/project/openid_connect/issues/2921095
  $client = $keycloak
    ->getClientInstance();
  $user_data = $client
    ->decodeIdToken($tokens['id_token']);

  // Whether a session_state was provided by the IdP.
  if (!isset($user_data['session_state'])) {
    return;
  }

  // Get the session ID (OpenID Connect 'session_state').
  $session_state = $user_data['session_state'];

  // Get the client ID (OpenID Connect audience = 'aud').
  $client_id = $user_data['aud'];
  $session_info = [
    KeycloakServiceInterface::KEYCLOAK_SESSION_ACCESS_TOKEN => $tokens['access_token'],
    KeycloakServiceInterface::KEYCLOAK_SESSION_REFRESH_TOKEN => $tokens['refresh_token'],
    KeycloakServiceInterface::KEYCLOAK_SESSION_ID_TOKEN => $tokens['id_token'],
    KeycloakServiceInterface::KEYCLOAK_SESSION_CLIENT_ID => $client_id,
    KeycloakServiceInterface::KEYCLOAK_SESSION_SESSION_ID => $session_state,
  ];
  $keycloak
    ->setSessionInfo($session_info);
}