You are here

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

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|false FALSE on failure, or 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.

Overrides OpenIDConnectClientInterface::retrieveTokens

File

includes/OpenIDConnectClientBase.class.php, line 135
Base class for OpenID Connect clients.

Class

OpenIDConnectClientBase
Base class for OpenID Connect clients.

Code

public function retrieveTokens($authorization_code) {

  // Exchange `code` for access token and ID token.
  $redirect_uri = OPENID_CONNECT_REDIRECT_PATH_BASE . '/' . $this->name;
  $post_data = array(
    'code' => $authorization_code,
    'client_id' => $this
      ->getSetting('client_id'),
    'client_secret' => $this
      ->getSetting('client_secret'),
    'redirect_uri' => url($redirect_uri, array(
      'absolute' => TRUE,
    )),
    'grant_type' => 'authorization_code',
  );
  $request_options = array(
    'method' => 'POST',
    'data' => drupal_http_build_query($post_data),
    'timeout' => 15,
    'headers' => array(
      'Content-Type' => 'application/x-www-form-urlencoded',
    ),
  );
  $endpoints = $this
    ->getEndpoints();
  $response = drupal_http_request($endpoints['token'], $request_options);
  if (!isset($response->error) && $response->code == 200) {
    $response_data = drupal_json_decode($response->data);
    $tokens = array(
      'id_token' => $response_data['id_token'],
      'access_token' => $response_data['access_token'],
    );
    if (array_key_exists('expires_in', $response_data)) {
      $tokens['expire'] = REQUEST_TIME + $response_data['expires_in'];
    }
    if (array_key_exists('refresh_token', $response_data)) {
      $tokens['refresh_token'] = $response_data['refresh_token'];
    }
    return $tokens;
  }
  else {
    openid_connect_log_request_error(__FUNCTION__, $this->name, $response);
    return FALSE;
  }
}