PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/google-api-php-client/src/auth/apiOAuth2.php

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