/library/Google/vendor/google/auth/src/Credentials/ServiceAccountCredentials.php

https://gitlab.com/vangtrangbac123/zinkaiuit.tk · PHP · 177 lines · 76 code · 12 blank · 89 comment · 7 complexity · 9b55e4f94b30e1c4f0f62241f88e7640 MD5 · raw file

  1. <?php
  2. /*
  3. * Copyright 2015 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace Google\Auth\Credentials;
  18. use Google\Auth\CredentialsLoader;
  19. use Google\Auth\OAuth2;
  20. /**
  21. * ServiceAccountCredentials supports authorization using a Google service
  22. * account.
  23. *
  24. * (cf https://developers.google.com/accounts/docs/OAuth2ServiceAccount)
  25. *
  26. * It's initialized using the json key file that's downloadable from developer
  27. * console, which should contain a private_key and client_email fields that it
  28. * uses.
  29. *
  30. * Use it with AuthTokenMiddleware to authorize http requests:
  31. *
  32. * use Google\Auth\Credentials\ServiceAccountCredentials;
  33. * use Google\Auth\Middleware\AuthTokenMiddleware;
  34. * use GuzzleHttp\Client;
  35. * use GuzzleHttp\HandlerStack;
  36. *
  37. * $sa = new ServiceAccountCredentials(
  38. * 'https://www.googleapis.com/auth/taskqueue',
  39. * '/path/to/your/json/key_file.json'
  40. * );
  41. * $middleware = new AuthTokenMiddleware($sa);
  42. * $stack = HandlerStack::create();
  43. * $stack->push($middleware);
  44. *
  45. * $client = new Client([
  46. * 'handler' => $stack,
  47. * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
  48. * 'auth' => 'google_auth' // authorize all requests
  49. * ]);
  50. *
  51. * $res = $client->get('myproject/taskqueues/myqueue');
  52. */
  53. class ServiceAccountCredentials extends CredentialsLoader
  54. {
  55. /**
  56. * The OAuth2 instance used to conduct authorization.
  57. *
  58. * @var OAuth2
  59. */
  60. protected $auth;
  61. /**
  62. * Create a new ServiceAccountCredentials.
  63. *
  64. * @param string|array $scope the scope of the access request, expressed
  65. * either as an Array or as a space-delimited String.
  66. * @param string|array $jsonKey JSON credential file path or JSON credentials
  67. * as an associative array
  68. * @param string $sub an email address account to impersonate, in situations when
  69. * the service account has been delegated domain wide access.
  70. */
  71. public function __construct(
  72. $scope,
  73. $jsonKey,
  74. $sub = null
  75. ) {
  76. if (is_string($jsonKey)) {
  77. if (!file_exists($jsonKey)) {
  78. throw new \InvalidArgumentException('file does not exist');
  79. }
  80. $jsonKeyStream = file_get_contents($jsonKey);
  81. if (!$jsonKey = json_decode($jsonKeyStream, true)) {
  82. throw new \LogicException('invalid json for auth config');
  83. }
  84. }
  85. if (!array_key_exists('client_email', $jsonKey)) {
  86. throw new \InvalidArgumentException(
  87. 'json key is missing the client_email field');
  88. }
  89. if (!array_key_exists('private_key', $jsonKey)) {
  90. throw new \InvalidArgumentException(
  91. 'json key is missing the private_key field');
  92. }
  93. $this->auth = new OAuth2([
  94. 'audience' => self::TOKEN_CREDENTIAL_URI,
  95. 'issuer' => $jsonKey['client_email'],
  96. 'scope' => $scope,
  97. 'signingAlgorithm' => 'RS256',
  98. 'signingKey' => $jsonKey['private_key'],
  99. 'sub' => $sub,
  100. 'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI,
  101. ]);
  102. }
  103. /**
  104. * @param callable $httpHandler
  105. *
  106. * @return array
  107. */
  108. public function fetchAuthToken(callable $httpHandler = null)
  109. {
  110. return $this->auth->fetchAuthToken($httpHandler);
  111. }
  112. /**
  113. * @return string
  114. */
  115. public function getCacheKey()
  116. {
  117. $key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey();
  118. if ($sub = $this->auth->getSub()) {
  119. $key .= ':' . $sub;
  120. }
  121. return $key;
  122. }
  123. /**
  124. * @return array
  125. */
  126. public function getLastReceivedToken()
  127. {
  128. return $this->auth->getLastReceivedToken();
  129. }
  130. /**
  131. * Updates metadata with the authorization token.
  132. *
  133. * @param array $metadata metadata hashmap
  134. * @param string $authUri optional auth uri
  135. * @param callable $httpHandler callback which delivers psr7 request
  136. *
  137. * @return array updated metadata hashmap
  138. */
  139. public function updateMetadata(
  140. $metadata,
  141. $authUri = null,
  142. callable $httpHandler = null
  143. ) {
  144. // scope exists. use oauth implementation
  145. $scope = $this->auth->getScope();
  146. if (!is_null($scope)) {
  147. return parent::updateMetadata($metadata, $authUri, $httpHandler);
  148. }
  149. // no scope found. create jwt with the auth uri
  150. $credJson = array(
  151. 'private_key' => $this->auth->getSigningKey(),
  152. 'client_email' => $this->auth->getIssuer(),
  153. );
  154. $jwtCreds = new ServiceAccountJwtAccessCredentials($credJson);
  155. return $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler);
  156. }
  157. /**
  158. * @param string $sub an email address account to impersonate, in situations when
  159. * the service account has been delegated domain wide access.
  160. */
  161. public function setSub($sub)
  162. {
  163. $this->auth->setSub($sub);
  164. }
  165. }