You are here

public function OAuth2Storage::getAuthorizationCode in OAuth2 Server 2.0.x

Same name and namespace in other branches
  1. 8 src/OAuth2Storage.php \Drupal\oauth2_server\OAuth2Storage::getAuthorizationCode()

Get authorization code.

Parameters

string $code: The authorization code string.

Return value

array|bool An authorization code array or false.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/OAuth2Storage.php, line 446

Class

OAuth2Storage
Provides Drupal OAuth2 storage for the library.

Namespace

Drupal\oauth2_server

Code

public function getAuthorizationCode($code) {

  /** @var \Drupal\oauth2_server\AuthorizationCodeInterface $code */
  $code = $this
    ->getStorageAuthorizationCode($code);
  if (!$code) {
    return FALSE;
  }
  $scopes = [];

  /** @var \Drupal\oauth2_server\ScopeInterface[] $scope_entities */
  $scope_entities = $code->scopes
    ->referencedEntities();
  foreach ($scope_entities as $scope) {
    $scopes[] = $scope->scope_id;
  }
  sort($scopes);

  // Return a code array in the format expected by the library.
  $code_array = [
    'server' => $code
      ->getClient()
      ->getServer()
      ->id(),
    'client_id' => $code
      ->getClient()->client_id,
    'user_id' => $code
      ->getUser()
      ->id(),
    'user_uuid' => $code
      ->getUser()
      ->uuid(),
    'authorization_code' => $code->code->value,
    'redirect_uri' => $code->redirect_uri->value,
    'expires' => (int) $code->expires->value,
    'scope' => implode(' ', $scopes),
    'id_token' => $code->id_token->value,
  ];

  // Examine the id_token and alter the OpenID Connect 'sub' property if
  // necessary. The 'sub' property is usually the user's UID, but this is
  // configurable for backwards compatibility reasons. See:
  // https://www.drupal.org/node/2274357#comment-9779467
  $sub_property = $this->configFactory
    ->get('oauth2_server.oauth')
    ->get('user_sub_property');
  if (!empty($code_array['id_token']) && $sub_property != 'uid') {
    $account = $code
      ->getUser();
    $desired_sub = $account->{$sub_property}->value;
    $parts = explode('.', $code_array['id_token']);
    $claims = json_decode(Utility::base64urlDecode($parts[1]), TRUE);
    if (isset($claims['sub']) && $desired_sub != $claims['sub']) {
      $claims['sub'] = $desired_sub;
      $parts[1] = Utility::base64urlEncode(json_encode($claims));
      $code_array['id_token'] = implode('.', $parts);
    }
  }
  return $code_array;
}