PageRenderTime 59ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/src/auth/Google_OAuth2.php

https://bitbucket.org/insigngmbh/googlephpapi
PHP | 453 lines | 294 code | 56 blank | 103 comment | 64 complexity | acb231b360ef09762189f89776789982 MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2008 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. require_once "Google_Verifier.php";
  18. require_once "Google_LoginTicket.php";
  19. require_once "service/Google_Utils.php";
  20. /**
  21. * Authentication class that deals with the OAuth 2 web-server authentication flow
  22. *
  23. * @author Chris Chabot <chabotc@google.com>
  24. * @author Chirag Shah <chirags@google.com>
  25. *
  26. */
  27. class Google_OAuth2 extends Google_Auth {
  28. public $clientId;
  29. public $clientSecret;
  30. public $developerKey;
  31. public $token;
  32. public $redirectUri;
  33. public $state;
  34. public $accessType = 'offline';
  35. public $approvalPrompt = 'force';
  36. public $requestVisibleActions;
  37. /** @var Google_AssertionCredentials $assertionCredentials */
  38. public $assertionCredentials;
  39. const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
  40. const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
  41. const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
  42. const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
  43. const CLOCK_SKEW_SECS = 300; // five minutes in seconds
  44. const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
  45. const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
  46. /**
  47. * Instantiates the class, but does not initiate the login flow, leaving it
  48. * to the discretion of the caller (which is done by calling authenticate()).
  49. */
  50. public function __construct() {
  51. global $apiConfig;
  52. if (! empty($apiConfig['developer_key'])) {
  53. $this->developerKey = $apiConfig['developer_key'];
  54. }
  55. if (! empty($apiConfig['oauth2_client_id'])) {
  56. $this->clientId = $apiConfig['oauth2_client_id'];
  57. }
  58. if (! empty($apiConfig['oauth2_client_secret'])) {
  59. $this->clientSecret = $apiConfig['oauth2_client_secret'];
  60. }
  61. if (! empty($apiConfig['oauth2_redirect_uri'])) {
  62. $this->redirectUri = $apiConfig['oauth2_redirect_uri'];
  63. }
  64. if (! empty($apiConfig['oauth2_access_type'])) {
  65. $this->accessType = $apiConfig['oauth2_access_type'];
  66. }
  67. if (! empty($apiConfig['oauth2_approval_prompt'])) {
  68. $this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
  69. }
  70. }
  71. /**
  72. * @param $service
  73. * @param string|null $code
  74. * @throws Google_AuthException
  75. * @return string
  76. */
  77. public function authenticate($service, $code = null) {
  78. if (!$code && isset($_GET['code'])) {
  79. $code = $_GET['code'];
  80. }
  81. if ($code) {
  82. // We got here from the redirect from a successful authorization grant, fetch the access token
  83. $request = Google_Client::$io->makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
  84. 'code' => $code,
  85. 'grant_type' => 'authorization_code',
  86. 'redirect_uri' => $this->redirectUri,
  87. 'client_id' => $this->clientId,
  88. 'client_secret' => $this->clientSecret
  89. )));
  90. if ($request->getResponseHttpCode() == 200) {
  91. $this->setAccessToken($request->getResponseBody());
  92. $this->token['created'] = time();
  93. return $this->getAccessToken();
  94. } else {
  95. $response = $request->getResponseBody();
  96. $decodedResponse = json_decode($response, true);
  97. if ($decodedResponse != null && $decodedResponse['error']) {
  98. $response = $decodedResponse['error'];
  99. }
  100. throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
  101. }
  102. }
  103. $authUrl = $this->createAuthUrl($service['scope']);
  104. header('Location: ' . $authUrl);
  105. return true;
  106. }
  107. /**
  108. * Create a URL to obtain user authorization.
  109. * The authorization endpoint allows the user to first
  110. * authenticate, and then grant/deny the access request.
  111. * @param string $scope The scope is expressed as a list of space-delimited strings.
  112. * @return string
  113. */
  114. public function createAuthUrl($scope) {
  115. $params = array(
  116. 'response_type=code',
  117. 'redirect_uri=' . urlencode($this->redirectUri),
  118. 'client_id=' . urlencode($this->clientId),
  119. 'scope=' . urlencode($scope),
  120. 'access_type=' . urlencode($this->accessType),
  121. 'approval_prompt=' . urlencode($this->approvalPrompt),
  122. );
  123. // if the list of scopes contains plus.login, add request_visible_actions
  124. // to auth URL
  125. if(strpos($scope, 'plus.login') && count($this->requestVisibleActions) > 0) {
  126. $params[] = 'request_visible_actions=' .
  127. urlencode($this->requestVisibleActions);
  128. }
  129. if (isset($this->state)) {
  130. $params[] = 'state=' . urlencode($this->state);
  131. }
  132. $params = implode('&', $params);
  133. return self::OAUTH2_AUTH_URL . "?$params";
  134. }
  135. /**
  136. * @param string $token
  137. * @throws Google_AuthException
  138. */
  139. public function setAccessToken($token) {
  140. $token = json_decode($token, true);
  141. if ($token == null) {
  142. throw new Google_AuthException('Could not json decode the token');
  143. }
  144. if (! isset($token['access_token'])) {
  145. throw new Google_AuthException("Invalid token format");
  146. }
  147. $this->token = $token;
  148. }
  149. public function getAccessToken() {
  150. return json_encode($this->token);
  151. }
  152. public function setDeveloperKey($developerKey) {
  153. $this->developerKey = $developerKey;
  154. }
  155. public function setState($state) {
  156. $this->state = $state;
  157. }
  158. public function setAccessType($accessType) {
  159. $this->accessType = $accessType;
  160. }
  161. public function setApprovalPrompt($approvalPrompt) {
  162. $this->approvalPrompt = $approvalPrompt;
  163. }
  164. public function setAssertionCredentials(Google_AssertionCredentials $creds) {
  165. $this->assertionCredentials = $creds;
  166. }
  167. /**
  168. * Include an accessToken in a given apiHttpRequest.
  169. * @param Google_HttpRequest $request
  170. * @return Google_HttpRequest
  171. * @throws Google_AuthException
  172. */
  173. public function sign(Google_HttpRequest $request) {
  174. // add the developer key to the request before signing it
  175. if ($this->developerKey) {
  176. $requestUrl = $request->getUrl();
  177. $requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
  178. $requestUrl .= 'key=' . urlencode($this->developerKey);
  179. $request->setUrl($requestUrl);
  180. }
  181. // Cannot sign the request without an OAuth access token.
  182. if (null == $this->token && null == $this->assertionCredentials) {
  183. return $request;
  184. }
  185. // Check if the token is set to expire in the next 30 seconds
  186. // (or has already expired).
  187. if ($this->isAccessTokenExpired()) {
  188. if ($this->assertionCredentials) {
  189. $this->refreshTokenWithAssertion();
  190. } else {
  191. if (! array_key_exists('refresh_token', $this->token)) {
  192. throw new Google_AuthException("The OAuth 2.0 access token has expired, "
  193. . "and a refresh token is not available. Refresh tokens are not "
  194. . "returned for responses that were auto-approved.");
  195. }
  196. $this->refreshToken($this->token['refresh_token']);
  197. }
  198. }
  199. // Add the OAuth2 header to the request
  200. $request->setRequestHeaders(
  201. array('Authorization' => 'Bearer ' . $this->token['access_token'])
  202. );
  203. return $request;
  204. }
  205. /**
  206. * Fetches a fresh access token with the given refresh token.
  207. * @param string $refreshToken
  208. * @return void
  209. */
  210. public function refreshToken($refreshToken) {
  211. $this->refreshTokenRequest(array(
  212. 'client_id' => $this->clientId,
  213. 'client_secret' => $this->clientSecret,
  214. 'refresh_token' => $refreshToken,
  215. 'grant_type' => 'refresh_token'
  216. ));
  217. }
  218. /**
  219. * Fetches a fresh access token with a given assertion token.
  220. * @param Google_AssertionCredentials $assertionCredentials optional.
  221. * @return void
  222. */
  223. public function refreshTokenWithAssertion($assertionCredentials = null) {
  224. if (!$assertionCredentials) {
  225. $assertionCredentials = $this->assertionCredentials;
  226. }
  227. $this->refreshTokenRequest(array(
  228. 'grant_type' => 'assertion',
  229. 'assertion_type' => $assertionCredentials->assertionType,
  230. 'assertion' => $assertionCredentials->generateAssertion(),
  231. ));
  232. }
  233. private function refreshTokenRequest($params) {
  234. $http = new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params);
  235. $request = Google_Client::$io->makeRequest($http);
  236. $code = $request->getResponseHttpCode();
  237. $body = $request->getResponseBody();
  238. if (200 == $code) {
  239. $token = json_decode($body, true);
  240. if ($token == null) {
  241. throw new Google_AuthException("Could not json decode the access token");
  242. }
  243. if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
  244. throw new Google_AuthException("Invalid token format");
  245. }
  246. $this->token['access_token'] = $token['access_token'];
  247. $this->token['expires_in'] = $token['expires_in'];
  248. $this->token['created'] = time();
  249. } else {
  250. throw new Google_AuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
  251. }
  252. }
  253. /**
  254. * Revoke an OAuth2 access token or refresh token. This method will revoke the current access
  255. * token, if a token isn't provided.
  256. * @throws Google_AuthException
  257. * @param string|null $token The token (access token or a refresh token) that should be revoked.
  258. * @return boolean Returns True if the revocation was successful, otherwise False.
  259. */
  260. public function revokeToken($token = null) {
  261. if (!$token) {
  262. $token = $this->token['access_token'];
  263. }
  264. $request = new Google_HttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
  265. $response = Google_Client::$io->makeRequest($request);
  266. $code = $response->getResponseHttpCode();
  267. if ($code == 200) {
  268. $this->token = null;
  269. return true;
  270. }
  271. return false;
  272. }
  273. /**
  274. * Returns if the access_token is expired.
  275. * @return bool Returns True if the access_token is expired.
  276. */
  277. public function isAccessTokenExpired() {
  278. if (null == $this->token) {
  279. return true;
  280. }
  281. // If the token is set to expire in the next 30 seconds.
  282. $expired = ($this->token['created']
  283. + ($this->token['expires_in'] - 30)) < time();
  284. return $expired;
  285. }
  286. // Gets federated sign-on certificates to use for verifying identity tokens.
  287. // Returns certs as array structure, where keys are key ids, and values
  288. // are PEM encoded certificates.
  289. private function getFederatedSignOnCerts() {
  290. // This relies on makeRequest caching certificate responses.
  291. $request = Google_Client::$io->makeRequest(new Google_HttpRequest(
  292. self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
  293. if ($request->getResponseHttpCode() == 200) {
  294. $certs = json_decode($request->getResponseBody(), true);
  295. if ($certs) {
  296. return $certs;
  297. }
  298. }
  299. throw new Google_AuthException(
  300. "Failed to retrieve verification certificates: '" .
  301. $request->getResponseBody() . "'.",
  302. $request->getResponseHttpCode());
  303. }
  304. /**
  305. * Verifies an id token and returns the authenticated apiLoginTicket.
  306. * Throws an exception if the id token is not valid.
  307. * The audience parameter can be used to control which id tokens are
  308. * accepted. By default, the id token must have been issued to this OAuth2 client.
  309. *
  310. * @param $id_token
  311. * @param $audience
  312. * @return Google_LoginTicket
  313. */
  314. public function verifyIdToken($id_token = null, $audience = null) {
  315. if (!$id_token) {
  316. $id_token = $this->token['id_token'];
  317. }
  318. $certs = $this->getFederatedSignonCerts();
  319. if (!$audience) {
  320. $audience = $this->clientId;
  321. }
  322. return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
  323. }
  324. // Verifies the id token, returns the verified token contents.
  325. // Visible for testing.
  326. function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
  327. $segments = explode(".", $jwt);
  328. if (count($segments) != 3) {
  329. throw new Google_AuthException("Wrong number of segments in token: $jwt");
  330. }
  331. $signed = $segments[0] . "." . $segments[1];
  332. $signature = Google_Utils::urlSafeB64Decode($segments[2]);
  333. // Parse envelope.
  334. $envelope = json_decode(Google_Utils::urlSafeB64Decode($segments[0]), true);
  335. if (!$envelope) {
  336. throw new Google_AuthException("Can't parse token envelope: " . $segments[0]);
  337. }
  338. // Parse token
  339. $json_body = Google_Utils::urlSafeB64Decode($segments[1]);
  340. $payload = json_decode($json_body, true);
  341. if (!$payload) {
  342. throw new Google_AuthException("Can't parse token payload: " . $segments[1]);
  343. }
  344. // Check signature
  345. $verified = false;
  346. foreach ($certs as $keyName => $pem) {
  347. $public_key = new Google_PemVerifier($pem);
  348. if ($public_key->verify($signed, $signature)) {
  349. $verified = true;
  350. break;
  351. }
  352. }
  353. if (!$verified) {
  354. throw new Google_AuthException("Invalid token signature: $jwt");
  355. }
  356. // Check issued-at timestamp
  357. $iat = 0;
  358. if (array_key_exists("iat", $payload)) {
  359. $iat = $payload["iat"];
  360. }
  361. if (!$iat) {
  362. throw new Google_AuthException("No issue time in token: $json_body");
  363. }
  364. $earliest = $iat - self::CLOCK_SKEW_SECS;
  365. // Check expiration timestamp
  366. $now = time();
  367. $exp = 0;
  368. if (array_key_exists("exp", $payload)) {
  369. $exp = $payload["exp"];
  370. }
  371. if (!$exp) {
  372. throw new Google_AuthException("No expiration time in token: $json_body");
  373. }
  374. if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
  375. throw new Google_AuthException(
  376. "Expiration time too far in future: $json_body");
  377. }
  378. $latest = $exp + self::CLOCK_SKEW_SECS;
  379. if ($now < $earliest) {
  380. throw new Google_AuthException(
  381. "Token used too early, $now < $earliest: $json_body");
  382. }
  383. if ($now > $latest) {
  384. throw new Google_AuthException(
  385. "Token used too late, $now > $latest: $json_body");
  386. }
  387. // TODO(beaton): check issuer field?
  388. // Check audience
  389. $aud = $payload["aud"];
  390. if ($aud != $required_audience) {
  391. throw new Google_AuthException("Wrong recipient, $aud != $required_audience: $json_body");
  392. }
  393. // All good.
  394. return new Google_LoginTicket($envelope, $payload);
  395. }
  396. }