You are here

public function OpenIDConnectClientBase::retrieveTokens in OpenID Connect / OAuth client 8

Same name and namespace in other branches
  1. 2.x 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|bool 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 FALSE if tokens could not be retrieved.

Overrides OpenIDConnectClientInterface::retrieveTokens

File

src/Plugin/OpenIDConnectClientBase.php, line 326

Class

OpenIDConnectClientBase
Base class for OpenID Connect client plugins.

Namespace

Drupal\openid_connect\Plugin

Code

public function retrieveTokens($authorization_code) {

  // 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(), TRUE);

    // Expected result.
    $tokens = [
      'id_token' => isset($response_data['id_token']) ? $response_data['id_token'] : NULL,
      'access_token' => isset($response_data['access_token']) ? $response_data['access_token'] : NULL,
    ];
    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) {
    $variables = [
      '@message' => 'Could not retrieve tokens',
      '@error_message' => $e
        ->getMessage(),
    ];
    if ($e instanceof RequestException && $e
      ->hasResponse()) {
      $response_body = $e
        ->getResponse()
        ->getBody()
        ->getContents();
      $variables['@error_message'] .= ' Response: ' . $response_body;
    }
    $this->loggerFactory
      ->get('openid_connect_' . $this->pluginId)
      ->error('@message. Details: @error_message', $variables);
    return FALSE;
  }
}