You are here

public function OpenIDConnectClientBase::retrieveTokens in OpenID Connect / OAuth client 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/OpenIDConnectClientBase.php \Drupal\openid_connect\Plugin\OpenIDConnectClientBase::retrieveTokens()

Retrieve access token and ID token.

Exchanging the authorization code that is received as the result of the authentication request for an access token and an ID token.

The ID token is a cryptographically signed JSON object encoded in base64. It contains identity information about the user. The access token can be sent to the login provider to obtain user profile information.

Parameters

string $authorization_code: Authorization code received as a result of the the authorization request.

Return value

array|null An associative array containing:

  • id_token: The ID token that holds user data.
  • access_token: Access token that can be used to obtain user profile information.
  • expire: Unix timestamp of the expiration date of the access token.

Or NULL if tokens could not be retrieved.

Overrides OpenIDConnectClientInterface::retrieveTokens

File

src/Plugin/OpenIDConnectClientBase.php, line 339

Class

OpenIDConnectClientBase
Base class for OpenID Connect client plugins.

Namespace

Drupal\openid_connect\Plugin

Code

public function retrieveTokens(string $authorization_code) : ?array {

  // Exchange `code` for access token and ID token.
  $redirect_uri = $this
    ->getRedirectUrl()
    ->toString();
  $endpoints = $this
    ->getEndpoints();
  $request_options = $this
    ->getRequestOptions($authorization_code, $redirect_uri);
  $client = $this->httpClient;
  try {
    $response = $client
      ->post($endpoints['token'], $request_options);
    $response_data = Json::decode((string) $response
      ->getBody());

    // Expected result.
    if (is_array($response_data)) {
      $tokens = [];
      if (isset($response_data['id_token'])) {
        $tokens['id_token'] = $response_data['id_token'];
      }
      if (isset($response_data['access_token'])) {
        $tokens['access_token'] = $response_data['access_token'];
      }
      if (array_key_exists('expires_in', $response_data)) {
        $tokens['expire'] = $this->dateTime
          ->getRequestTime() + $response_data['expires_in'];
      }
      if (array_key_exists('refresh_token', $response_data)) {
        $tokens['refresh_token'] = $response_data['refresh_token'];
      }
      return $tokens;
    }
  } catch (\Exception $e) {
    $error_message = $e
      ->getMessage();
    if ($e instanceof RequestException && $e
      ->hasResponse()) {
      $error_message .= ' Response: ' . $e
        ->getResponse()
        ->getBody()
        ->getContents();
    }
    $this->loggerFactory
      ->get('openid_connect_' . $this->pluginId)
      ->error('Could not retrieve tokens. Details: @error_message', [
      '@error_message' => $error_message,
    ]);
  }
  return NULL;
}