You are here

class TestController in OAuth2 Client 8

Class TestController.

@package Drupal\oauth2_client_test\Controller

Hierarchy

Expanded class hierarchy of TestController

File

tests/oauth2_client_test/src/Controller/TestController.php, line 14

Namespace

Drupal\oauth2_client_test\Controller
View source
class TestController extends ControllerBase {

  /**
   * Trying test clients.
   *
   * Call them by opening in browser:
   *   - $base_url/oauth2/test/client-credentials
   *   - $base_url/oauth2/test/user-password
   *   - $base_url/oauth2/test/server-side
   *   - $base_url/oauth2/test/server-side-auto
   *   - $base_url/oauth2/test/wrong-client-id
   *   - $base_url/oauth2/test/wrong-client-secret
   *   - $base_url/oauth2/test/wrong-token-endpoint
   *   - $base_url/oauth2/test/wrong-auth-flow
   *   - $base_url/oauth2/test/wrong-username
   *   - $base_url/oauth2/test/wrong-password
   *   - $base_url/oauth2/test/wrong-scope
   *   - $base_url/oauth2/test/wrong-authorization-endpoint
   *   - $base_url/oauth2/test/wrong-redirect-uri.
   */
  public function callback($client_name) {
    try {

      // Get an access token and output it.
      $oauth2_client = oauth2_client_load($client_name);
      $access_token = $oauth2_client
        ->getAccessToken();
      return [
        '#markup' => "access_token: {$access_token}",
      ];
    } catch (\Exception $e) {
      return [
        '#markup' => $e
          ->getMessage(),
      ];
    }
  }

  /**
   * Client Integration.
   *
   * Use the client 'client2' for getting an authorization code.
   * This is done with the help of the module oauth2_client,
   * because 'client2' is registered for it (its return_uri belongs
   * to oauth2_client).
   * Before jumping to $authentication_uri, register an internal
   * redirect with oauth2_client.
   *
   * Try it by opening in browser:
   *   - $base_url/oauth2/test-client-integration
   */
  public function clientIntegration() {
    $state = \Drupal::csrfToken()
      ->get('test_client');
    oauth2_client_set_redirect($state, [
      'uri' => 'oauth2/test-authorized',
      'params' => [
        'extra_param' => 'This will be appended to the request on redirect.',
      ],
    ]);
    $query_params = [
      'response_type' => 'code',
      'client_id' => 'client2',
      'redirect_uri' => oauth2_client_get_redirect_uri(),
      'state' => $state,
    ];
    $endpoint = Url::fromUserInput('oauth2/authorize', [
      'absolute' => TRUE,
    ])
      ->toString();
    $authentication_uri = $endpoint . '?' . http_build_query($query_params);
    return new RedirectResponse($authentication_uri);
  }

  /**
   * Authorized.
   *
   * The oauth2 server will redirect to the registered redirect_uri,
   * which is handled by the oauth2_client, but then oauth2_client
   * will redirect to the path 'oauth2/test/authorized', which comes
   * here. This is because we registered a redirect on the oauth2_client
   * before jumping to $authentication_uri. While redirecting, oauth2_client
   * will also append to the request the 'extra_param'.
   */
  public function authorized() {
    if (!\Drupal::csrfToken()
      ->validate($_GET['state'], 'test_client')) {
      return [
        '#markup' => "The parameter 'state' is wrong.\n",
      ];
    }
    $extra_param = $_GET['extra_param'];
    print "extra_param: {$extra_param} <br/>\n";
    $options = [
      'method' => 'POST',
      'data' => http_build_query([
        'grant_type' => 'authorization_code',
        'code' => $_GET['code'],
        'redirect_uri' => oauth2_client_get_redirect_uri(),
      ]),
      'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Authorization' => 'Basic ' . base64_encode('client2:secret2'),
      ],
      'context' => stream_context_create([
        'ssl' => [
          'verify_peer' => FALSE,
          'verify_peer_name' => FALSE,
        ],
      ]),
    ];
    $token_endpoint = Url::fromUserInput('oauth2/token', [
      'absolute' => TRUE,
    ])
      ->toString();
    $result = \Drupal::httpClient()
      ->get($token_endpoint, $options);
    $token = json_decode($result
      ->getBody()
      ->getContents());
    return [
      '#markup' => 'access_token: ' . $token->access_token,
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
TestController::authorized public function Authorized.
TestController::callback public function Trying test clients.
TestController::clientIntegration public function Client Integration.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.