You are here

class OpenIDConnectGenericClient in OpenID Connect / OAuth client 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/OpenIDConnectClient/OpenIDConnectGenericClient.php \Drupal\openid_connect\Plugin\OpenIDConnectClient\OpenIDConnectGenericClient

Generic OAuth 2.0 OpenID Connect client.

Used primarily to login to Drupal sites powered by oauth2_server or PHP sites powered by oauth2-server-php.

Plugin annotation


@OpenIDConnectClient(
  id = "generic",
  label = @Translation("Generic OAuth 2.0")
)

Hierarchy

Expanded class hierarchy of OpenIDConnectGenericClient

File

src/Plugin/OpenIDConnectClient/OpenIDConnectGenericClient.php, line 19

Namespace

Drupal\openid_connect\Plugin\OpenIDConnectClient
View source
class OpenIDConnectGenericClient extends OpenIDConnectClientBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() : array {
    return [
      'issuer_url' => '',
      'authorization_endpoint' => 'https://example.com/oauth2/authorize',
      'token_endpoint' => 'https://example.com/oauth2/token',
      'userinfo_endpoint' => 'https://example.com/oauth2/userinfo',
      'end_session_endpoint' => '',
      'scopes' => [
        'openid',
        'email',
      ],
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) : array {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['use_well_known'] = [
      '#title' => $this
        ->t('Auto discover endpoints'),
      '#type' => 'checkbox',
      '#description' => $this
        ->t('Requires IDP support for "<a href="@url" target="_blank">OpenID Connect Discovery</a>".', [
        '@url' => 'https://openid.net/specs/openid-connect-discovery-1_0.html',
      ]),
      '#default_value' => !empty($this->configuration['issuer_url']),
    ];

    // Auto discover fields.
    $form['issuer_url'] = [
      '#title' => $this
        ->t('Issuer URL'),
      '#type' => 'url',
      '#default_value' => $this->configuration['issuer_url'],
      '#states' => [
        'visible' => [
          ':input[name="settings[use_well_known]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['authorization_endpoint'] = [
      '#title' => $this
        ->t('Authorization endpoint'),
      '#type' => 'url',
      '#default_value' => $this->configuration['authorization_endpoint'],
      '#states' => [
        'visible' => [
          ':input[name="settings[use_well_known]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['token_endpoint'] = [
      '#title' => $this
        ->t('Token endpoint'),
      '#type' => 'url',
      '#default_value' => $this->configuration['token_endpoint'],
      '#states' => [
        'visible' => [
          ':input[name="settings[use_well_known]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['userinfo_endpoint'] = [
      '#title' => $this
        ->t('UserInfo endpoint'),
      '#type' => 'url',
      '#default_value' => $this->configuration['userinfo_endpoint'],
      '#states' => [
        'visible' => [
          ':input[name="settings[use_well_known]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['end_session_endpoint'] = [
      '#title' => $this
        ->t('End Session endpoint'),
      '#type' => 'url',
      '#default_value' => $this->configuration['end_session_endpoint'],
      '#states' => [
        'visible' => [
          ':input[name="settings[use_well_known]"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['scopes'] = [
      '#title' => $this
        ->t('Scopes'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('Custom scopes, separated by spaces, for example: openid email'),
      '#default_value' => implode(' ', $this->configuration['scopes']),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
    $configuration = $form_state
      ->getValues();
    if ($configuration['use_well_known']) {
      $endpoints = $this
        ->autoDiscoverEndpoints($configuration['issuer_url']);
      if ($endpoints === FALSE) {
        $form_state
          ->setErrorByName('issuer_url', $this
          ->t('The issuer URL @url appears to be invalid.', [
          '@url' => $configuration['issuer_url'],
        ]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $configuration = $form_state
      ->getValues();
    if ($configuration['use_well_known']) {
      $endpoints = $this
        ->autoDiscoverEndpoints($configuration['issuer_url']);
      $this
        ->setConfiguration([
        'authorization_endpoint' => $endpoints['authorization_endpoint'],
        'token_endpoint' => $endpoints['token_endpoint'],
        'userinfo_endpoint' => $endpoints['userinfo_endpoint'],
      ]);
    }

    // Don't store use_well_known in the configuration, as it is set using the
    // value of the issuer_url setting.
    $this
      ->unsetConfigurationKeys([
      'use_well_known',
    ]);
    if (!empty($configuration['scopes'])) {
      $this
        ->setConfiguration([
        'scopes' => explode(' ', $configuration['scopes']),
      ]);
    }
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function getClientScopes() : ?array {
    return $this->configuration['scopes'];
  }

  /**
   * Performs endpoint discovery.
   *
   * @param string $issuer_url
   *   The issuer URL.
   *
   * @return array|false
   *   Array with discovered endpoints; FALSE on failure to fetch data or the
   *   JSON response not containing the three *required* endpoints
   *   (authorization, token, userinfo).
   */
  protected function autoDiscoverEndpoints(string $issuer_url = '') {
    static $results = [];
    if (empty($issuer_url)) {
      $issuer_url = $this->configuration['issuer_url'];
    }
    if (!isset($results[$issuer_url])) {
      $results[$issuer_url] = $this->autoDiscover
        ->fetch($issuer_url);
    }
    $result = $results[$issuer_url];
    if ($result && isset($result['authorization_endpoint']) && isset($result['token_endpoint']) && isset($result['userinfo_endpoint'])) {
      return $result;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getEndpoints() : array {
    return [
      'authorization' => $this->configuration['authorization_endpoint'],
      'token' => $this->configuration['token_endpoint'],
      'userinfo' => $this->configuration['userinfo_endpoint'],
      'end_session' => $this->configuration['end_session_endpoint'],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OpenIDConnectClientBase::$autoDiscover protected property The OpenID well-known discovery service.
OpenIDConnectClientBase::$dateTime protected property The datetime.time service.
OpenIDConnectClientBase::$httpClient protected property The HTTP client to fetch the feed data with.
OpenIDConnectClientBase::$languageManager protected property The language manager.
OpenIDConnectClientBase::$loggerFactory protected property The logger factory used for logging.
OpenIDConnectClientBase::$pageCacheKillSwitch protected property Page cache kill switch.
OpenIDConnectClientBase::$parentEntityId protected property The parent entity identifier.
OpenIDConnectClientBase::$requestStack protected property The request stack used to access request globals.
OpenIDConnectClientBase::$stateToken protected property The OpenID state token service.
OpenIDConnectClientBase::authorize public function Redirects the user to the authorization endpoint. Overrides OpenIDConnectClientInterface::authorize 3
OpenIDConnectClientBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
OpenIDConnectClientBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
OpenIDConnectClientBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
OpenIDConnectClientBase::getLabel public function Return the plugin label as defined in the annotation. Overrides OpenIDConnectClientInterface::getLabel
OpenIDConnectClientBase::getParentEntityId public function Returns the parent entity ID. Overrides OpenIDConnectClientInterface::getParentEntityId
OpenIDConnectClientBase::getRedirectUrl protected function Returns the redirect URL.
OpenIDConnectClientBase::getRequestOptions protected function Helper function for request options.
OpenIDConnectClientBase::getUrlOptions protected function Helper function for URL options.
OpenIDConnectClientBase::retrieveTokens public function Retrieve access token and ID token. Overrides OpenIDConnectClientInterface::retrieveTokens
OpenIDConnectClientBase::retrieveUserInfo public function Retrieves user info: additional user profile data. Overrides OpenIDConnectClientInterface::retrieveUserInfo 4
OpenIDConnectClientBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
OpenIDConnectClientBase::setParentEntityId public function Sets the parent entity ID. Overrides OpenIDConnectClientInterface::setParentEntityId
OpenIDConnectClientBase::unsetConfigurationKeys protected function Unsets some elements of the configuration.
OpenIDConnectClientBase::usesUserInfo public function Check if the client uses the userinfo endpoint. Overrides OpenIDConnectClientInterface::usesUserInfo
OpenIDConnectClientBase::__construct public function The constructor. Overrides PluginBase::__construct
OpenIDConnectGenericClient::autoDiscoverEndpoints protected function Performs endpoint discovery.
OpenIDConnectGenericClient::buildConfigurationForm public function Form constructor. Overrides OpenIDConnectClientBase::buildConfigurationForm
OpenIDConnectGenericClient::defaultConfiguration public function Gets default configuration for this plugin. Overrides OpenIDConnectClientBase::defaultConfiguration
OpenIDConnectGenericClient::getClientScopes public function Gets an array of of scopes. Overrides OpenIDConnectClientBase::getClientScopes
OpenIDConnectGenericClient::getEndpoints public function Returns an array of endpoints. Overrides OpenIDConnectClientInterface::getEndpoints
OpenIDConnectGenericClient::submitConfigurationForm public function Form submission handler. Overrides OpenIDConnectClientBase::submitConfigurationForm
OpenIDConnectGenericClient::validateConfigurationForm public function Form validation handler. Overrides OpenIDConnectClientBase::validateConfigurationForm
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass().
PluginWithFormsTrait::hasFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass().
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.