You are here

protected function OAuth2Client::getToken in OAuth2 Client 8

Get and return an access token for the grant_type given in $params.

3 calls to OAuth2Client::getToken()
OAuth2Client::getAccessToken in src/Service/OAuth2Client.php
OAuth2Client::getTokenRefreshToken in src/Service/OAuth2Client.php
Get a new access_token using the refresh_token.
OAuth2Client::getTokenServerSide in src/Service/OAuth2Client.php
Get an access_token using the server-side (authorization code) flow.

File

src/Service/OAuth2Client.php, line 446

Class

OAuth2Client
OAuth2Client service.

Namespace

Drupal\oauth2_client\Service

Code

protected function getToken($data) {
  if (array_key_exists('scope', $data) && $data['scope'] === NULL) {
    unset($data['scope']);
  }
  $client_id = $this->params['client_id'];
  $client_secret = $this->params['client_secret'];
  $token_endpoint = $this->params['token_endpoint'];
  $data['client_id'] = $client_id;
  $data['client_secret'] = $client_secret;
  $options = [
    'form_params' => $data,
    'headers' => [
      'Content-Type' => 'application/x-www-form-urlencoded',
      'Authorization' => 'Basic ' . base64_encode("{$client_id}:{$client_secret}"),
    ],
  ];
  if ($this->params['skip-ssl-verification']) {
    $options['context'] = stream_context_create([
      'ssl' => [
        'verify_peer' => FALSE,
        'verify_peer_name' => FALSE,
      ],
    ]);
  }
  $response = $this->httpClient
    ->request('POST', $token_endpoint, $options);
  $response_data = (string) $response
    ->getBody();
  if (empty($response_data)) {
    throw new \Exception($this
      ->t("Failed to get an access token of grant_type @grant_type.\nError: @result_error", [
      '@grant_type' => $data['grant_type'],
    ]));
  }
  $serializer = new Serializer([
    new GetSetMethodNormalizer(),
  ], [
    'json' => new JsonEncoder(),
  ]);
  $token = $serializer
    ->decode($response_data, 'json');
  if (!isset($token['expiration_time'])) {

    // Some providers do not return an 'expires_in' value, so we
    // set a default of an hour. If the token expires dies within that time,
    // the system will request a new token automatically.
    $token['expiration_time'] = \Drupal::time()
      ->getRequestTime() + 3600;
  }
  return $token;
}