You are here

public function Keycloak::authorize in Keycloak OpenID Connect 8

Redirects the user to the authorization endpoint.

The authorization endpoint authenticates the user and returns them to the redirect_uri specified previously with an authorization code that can be exchanged for an access token.

Parameters

string $scope: Name of scope(s) that with user consent will provide access to otherwise restricted user data. Defaults to "openid email".

Return value

\Symfony\Component\HttpFoundation\Response A response object.

Overrides OpenIDConnectClientBase::authorize

File

src/Plugin/OpenIDConnectClient/Keycloak.php, line 128

Class

Keycloak
OpenID Connect client for Keycloak.

Namespace

Drupal\keycloak\Plugin\OpenIDConnectClient

Code

public function authorize($scope = 'openid email') {
  $language_manager = \Drupal::languageManager();
  $language_none = $language_manager
    ->getLanguage(LanguageInterface::LANGCODE_NOT_APPLICABLE);
  $redirect_uri = Url::fromRoute('openid_connect.redirect_controller_redirect', [
    'client_name' => $this->pluginId,
  ], [
    'absolute' => TRUE,
    'language' => $language_none,
  ])
    ->toString(TRUE);
  $url_options = [
    'query' => [
      'client_id' => $this->configuration['client_id'],
      'response_type' => 'code',
      'scope' => $scope,
      'redirect_uri' => $redirect_uri
        ->getGeneratedUrl(),
      'state' => OpenIDConnectStateToken::create(),
    ],
  ];

  // Whether to add language parameter.
  if ($this->keycloak
    ->isI18nEnabled()) {

    // Get current language.
    $langcode = $language_manager
      ->getCurrentLanguage()
      ->getId();

    // Map Drupal language code to Keycloak language identifier.
    // This is required for some languages, as Drupal uses IETF
    // script codes, while Keycloak may use IETF region codes.
    $languages = $this->keycloak
      ->getI18nMapping();
    if (!empty($languages[$langcode])) {
      $langcode = $languages[$langcode]['locale'];
    }

    // Add parameter to request query, so the Keycloak login/register
    // pages will load using the right locale.
    $url_options['query']['kc_locale'] = $langcode;
  }
  $endpoints = $this
    ->getEndpoints();

  // Clear _GET['destination'] because we need to override it.
  $this->requestStack
    ->getCurrentRequest()->query
    ->remove('destination');
  $authorization_endpoint = Url::fromUri($endpoints['authorization'], $url_options)
    ->toString(TRUE);
  $response = new TrustedRedirectResponse($authorization_endpoint
    ->getGeneratedUrl());

  // We can't cache the response, since this will prevent the state to be
  // added to the session. The kill switch will prevent the page getting
  // cached for anonymous users when page cache is active.
  \Drupal::service('page_cache_kill_switch')
    ->trigger();
  return $response;
}