You are here

class Oauth2GrantManager in Simple OAuth (OAuth2) & OpenID Connect 5.x

Same name and namespace in other branches
  1. 8.4 src/Plugin/Oauth2GrantManager.php \Drupal\simple_oauth\Plugin\Oauth2GrantManager
  2. 8.2 src/Plugin/Oauth2GrantManager.php \Drupal\simple_oauth\Plugin\Oauth2GrantManager
  3. 8.3 src/Plugin/Oauth2GrantManager.php \Drupal\simple_oauth\Plugin\Oauth2GrantManager

Provides the OAuth2 Grant plugin manager.

Hierarchy

Expanded class hierarchy of Oauth2GrantManager

1 string reference to 'Oauth2GrantManager'
simple_oauth.services.yml in ./simple_oauth.services.yml
simple_oauth.services.yml
1 service uses Oauth2GrantManager
plugin.manager.oauth2_grant.processor in ./simple_oauth.services.yml
Drupal\simple_oauth\Plugin\Oauth2GrantManager

File

src/Plugin/Oauth2GrantManager.php, line 27

Namespace

Drupal\simple_oauth\Plugin
View source
class Oauth2GrantManager extends DefaultPluginManager implements Oauth2GrantManagerInterface {

  /**
   * @var \League\OAuth2\Server\Repositories\ClientRepositoryInterface
   */
  protected $clientRepository;

  /**
   * @var \League\OAuth2\Server\Repositories\ScopeRepositoryInterface
   */
  protected $scopeRepository;

  /**
   * @var \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface
   */
  protected $accessTokenRepository;

  /**
   * @var \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface
   */
  protected $refreshTokenRepository;

  /**
   * @var \League\OAuth2\Server\ResponseTypes\ResponseTypeInterface
   */
  protected $responseType;

  /**
   * @var string
   */
  protected $privateKeyPath;

  /**
   * @var string
   */
  protected $publicKeyPath;

  /**
   * @var \DateTime
   */
  protected $expiration;

  /**
   * @var \League\OAuth2\Server\AuthorizationServer
   */
  protected $server;

  /**
   * The file system.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * Constructor for Oauth2GrantManager objects.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   * @param \League\OAuth2\Server\Repositories\ClientRepositoryInterface $client_repository
   *   The client repository.
   * @param \League\OAuth2\Server\Repositories\ScopeRepositoryInterface $scope_repository
   *   The scope repository.
   * @param \League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface $access_token_repository
   *   The access token repository.
   * @param \League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface $refresh_token_repository
   *   The refresh token repository.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \League\OAuth2\Server\ResponseTypes\ResponseTypeInterface $response_type
   *   The authorization server response type.
   *
   * @throws \Exception
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ClientRepositoryInterface $client_repository, ScopeRepositoryInterface $scope_repository, AccessTokenRepositoryInterface $access_token_repository, RefreshTokenRepositoryInterface $refresh_token_repository, ConfigFactoryInterface $config_factory, ResponseTypeInterface $response_type = NULL) {
    parent::__construct('Plugin/Oauth2Grant', $namespaces, $module_handler, 'Drupal\\simple_oauth\\Plugin\\Oauth2GrantInterface', 'Drupal\\simple_oauth\\Annotation\\Oauth2Grant');
    $this
      ->alterInfo('simple_oauth_oauth2_grant_info');
    $this
      ->setCacheBackend($cache_backend, 'simple_oauth_oauth2_grant_plugins');
    $this->clientRepository = $client_repository;
    $this->scopeRepository = $scope_repository;
    $this->accessTokenRepository = $access_token_repository;
    $this->refreshTokenRepository = $refresh_token_repository;
    $this->responseType = $response_type;
    $settings = $config_factory
      ->get('simple_oauth.settings');
    $this
      ->setKeyPaths($settings);
    $this->expiration = new \DateInterval(sprintf('PT%dS', $settings
      ->get('access_token_expiration')));
  }

  /**
   * {@inheritdoc}
   */
  public function getAuthorizationServer($grant_type, Consumer $client = NULL) {
    try {

      /** @var \Drupal\simple_oauth\Plugin\Oauth2GrantInterface $plugin */
      $plugin = $this
        ->createInstance($grant_type);
    } catch (PluginNotFoundException $exception) {
      throw OAuthServerException::invalidGrant('Check the configuration to see if the grant is enabled.');
    }
    $this
      ->checkKeyPaths();
    $salt = Settings::getHashSalt();

    // The hash salt must be at least 32 characters long.
    if (Core::ourStrlen($salt) < 32) {
      throw OAuthServerException::serverError('Hash salt must be at least 32 characters long.');
    }
    if (empty($this->server)) {
      $this->server = new AuthorizationServer($this->clientRepository, $this->accessTokenRepository, $this->scopeRepository, $this
        ->fileSystem()
        ->realpath($this->privateKeyPath), Core::ourSubstr($salt, 0, 32), $this->responseType);
    }
    $grant = $plugin
      ->getGrantType();

    // Optionally enable PKCE.
    if ($client && $grant instanceof AuthCodeGrant) {
      $client_has_pkce_enabled = $client
        ->hasField('pkce') && $client
        ->get('pkce')
        ->first()->value;
      if (!$client_has_pkce_enabled) {
        $grant
          ->disableRequireCodeChallengeForPublicClients();
      }
    }

    // Enable the grant on the server with a token TTL of X hours.
    $this->server
      ->enableGrantType($grant, $this->expiration);
    return $this->server;
  }

  /**
   * Set the public and private key paths.
   *
   * @param \Drupal\Core\Config\ImmutableConfig $settings
   *   The Simple OAuth settings configuration object.
   */
  protected function setKeyPaths(ImmutableConfig $settings) {
    $this->publicKeyPath = $settings
      ->get('public_key');
    $this->privateKeyPath = $settings
      ->get('private_key');
  }

  /**
   * @throws \League\OAuth2\Server\Exception\OAuthServerException
   *   If one or both keys are not set properly.
   */
  protected function checkKeyPaths() {
    if (!file_exists($this->publicKeyPath) || !file_exists($this->privateKeyPath)) {
      throw OAuthServerException::serverError(sprintf('You need to set the OAuth2 secret and private keys.'));
    }
  }

  /**
   * Lazy loads the file system.
   *
   * @return \Drupal\Core\File\FileSystemInterface
   *   The file system service.
   */
  protected function fileSystem() : FileSystemInterface {
    if (!isset($this->fileSystem)) {
      $this->fileSystem = \Drupal::service('file_system');
    }
    return $this->fileSystem;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional namespaces the annotation discovery mechanism should scan for annotation definitions.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition() if additional processing of plugins is necessary or helpful for development purposes. 9
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object that implements \Traversable which contains the root paths keyed by the corresponding namespace to look for plugin implementations.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins, or FALSE if the plugins are in the top level of the namespace.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 1
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides CachedDiscoveryInterface::clearCachedDefinitions 6
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::findDefinitions protected function Finds plugin definitions. 7
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 12
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::processDefinition public function Performs extra processing on plugin definitions. 13
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 3
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DefaultPluginManager::useCaches public function Disable the use of caches. Overrides CachedDiscoveryInterface::useCaches 1
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryCachedTrait::getDefinition public function Overrides DiscoveryTrait::getDefinition 3
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
Oauth2GrantManager::$accessTokenRepository protected property
Oauth2GrantManager::$clientRepository protected property
Oauth2GrantManager::$expiration protected property
Oauth2GrantManager::$fileSystem protected property The file system.
Oauth2GrantManager::$privateKeyPath protected property
Oauth2GrantManager::$publicKeyPath protected property
Oauth2GrantManager::$refreshTokenRepository protected property
Oauth2GrantManager::$responseType protected property
Oauth2GrantManager::$scopeRepository protected property
Oauth2GrantManager::$server protected property
Oauth2GrantManager::checkKeyPaths protected function
Oauth2GrantManager::fileSystem protected function Lazy loads the file system.
Oauth2GrantManager::getAuthorizationServer public function Gets the authorization server. Overrides Oauth2GrantManagerInterface::getAuthorizationServer
Oauth2GrantManager::setKeyPaths protected function Set the public and private key paths.
Oauth2GrantManager::__construct public function Constructor for Oauth2GrantManager objects. Overrides DefaultPluginManager::__construct
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::createInstance public function Creates a pre-configured instance of a plugin. Overrides FactoryInterface::createInstance 12
PluginManagerBase::getInstance public function Gets a preconfigured instance of a plugin. Overrides MapperInterface::getInstance 6
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag.
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.