You are here

public function OAuth2Client::getAccessToken in OAuth2 Client 8

Throws

\Exception

Overrides OAuth2ClientInterface::getAccessToken

File

src/Service/OAuth2Client.php, line 173

Class

OAuth2Client
OAuth2Client service.

Namespace

Drupal\oauth2_client\Service

Code

public function getAccessToken($redirect = TRUE) {

  // Check wheather the existing token has expired.
  // We take the expiration time to be shorter by 10 sec
  // in order to account for any delays during the request.
  // Usually a token is valid for 1 hour, so making
  // the expiration time shorter by 10 sec is insignificant.
  // However it should be kept in mind during the tests,
  // where the expiration time is much shorter.
  $expiration_time = $this->token['expiration_time'];
  if ($expiration_time > time() + 10) {

    // The existing token can still be used.
    return $this->token['access_token'];
  }
  try {

    // Try to use refresh_token.
    $token = $this
      ->getTokenRefreshToken();
  } catch (\Exception $e) {

    // Get a token.
    switch ($this->params['auth_flow']) {
      case 'client-credentials':
        $token = $this
          ->getToken([
          'grant_type' => 'client_credentials',
          'scope' => $this->params['scope'],
        ]);
        break;
      case 'user-password':
        $token = $this
          ->getToken([
          'grant_type' => 'password',
          'username' => $this->params['username'],
          'password' => $this->params['password'],
          'scope' => $this->params['scope'],
        ]);
        break;
      case 'server-side':
        if ($redirect) {
          $token = $this
            ->getTokenServerSide();
        }
        else {
          $this
            ->clearToken();
          return NULL;
        }
        break;
      default:
        throw new \Exception(t('Unknown authorization flow "@auth_flow". Supported values for auth_flow are: client-credentials, user-password, server-side.', [
          '@auth_flow' => $this->params['auth_flow'],
        ]));
    }
  }

  // Store the token (on session as well).
  $this->token = $token;
  $tokens = $this->tempstore
    ->get('token');
  $tokens[$this->id] = $token;
  $this->tempstore
    ->set('token', $tokens);

  // Redirect to the original path (if this is a redirection
  // from the server-side flow).
  self::redirect();

  // Return the token.
  return $token['access_token'];
}