PageRenderTime 47ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/general/ApiOAuth2Test.php

https://gitlab.com/oytunistrator/google-api-php-client
PHP | 256 lines | 197 code | 21 blank | 38 comment | 1 complexity | 7feb114793ae1c2b444ac77dc1fad9a9 MD5 | raw file
  1. <?php
  2. /**
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. class ApiOAuth2Test extends BaseTest
  21. {
  22. public function testSign()
  23. {
  24. $client = $this->getClient();
  25. $oauth = new Google_Auth_OAuth2($client);
  26. $client->setClientId('clientId1');
  27. $client->setClientSecret('clientSecret1');
  28. $client->setRedirectUri('http://localhost');
  29. $client->setDeveloperKey('devKey');
  30. $client->setAccessType('offline');
  31. $client->setApprovalPrompt('force');
  32. $client->setRequestVisibleActions('http://foo');
  33. $req = new Google_Http_Request('http://localhost');
  34. $req = $oauth->sign($req);
  35. $this->assertEquals('http://localhost?key=devKey', $req->getUrl());
  36. // test accessToken
  37. $oauth->setAccessToken(
  38. json_encode(
  39. array(
  40. 'access_token' => 'ACCESS_TOKEN',
  41. 'created' => time(),
  42. 'expires_in' => '3600'
  43. )
  44. )
  45. );
  46. $req = $oauth->sign($req);
  47. $auth = $req->getRequestHeader('authorization');
  48. $this->assertEquals('Bearer ACCESS_TOKEN', $auth);
  49. }
  50. public function testRevokeAccess()
  51. {
  52. $accessToken = "ACCESS_TOKEN";
  53. $refreshToken = "REFRESH_TOKEN";
  54. $accessToken2 = "ACCESS_TOKEN_2";
  55. $token = "";
  56. $client = $this->getClient();
  57. $response = $this->getMock("Google_Http_Request", array(), array(''));
  58. $response->expects($this->any())
  59. ->method('getResponseHttpCode')
  60. ->will($this->returnValue(200));
  61. $io = $this->getMock("Google_IO_Stream", array(), array($client));
  62. $io->expects($this->any())
  63. ->method('makeRequest')
  64. ->will(
  65. $this->returnCallback(
  66. function ($request) use (&$token, $response) {
  67. $elements = array();
  68. parse_str($request->getPostBody(), $elements);
  69. $token = isset($elements['token']) ? $elements['token'] : null;
  70. return $response;
  71. }
  72. )
  73. );
  74. $client->setIo($io);
  75. // Test with access token.
  76. $oauth = new Google_Auth_OAuth2($client);
  77. $oauth->setAccessToken(
  78. json_encode(
  79. array(
  80. 'access_token' => $accessToken,
  81. 'created' => time(),
  82. 'expires_in' => '3600'
  83. )
  84. )
  85. );
  86. $this->assertTrue($oauth->revokeToken());
  87. $this->assertEquals($accessToken, $token);
  88. // Test with refresh token.
  89. $oauth = new Google_Auth_OAuth2($client);
  90. $oauth->setAccessToken(
  91. json_encode(
  92. array(
  93. 'access_token' => $accessToken,
  94. 'refresh_token' => $refreshToken,
  95. 'created' => time(),
  96. 'expires_in' => '3600'
  97. )
  98. )
  99. );
  100. $this->assertTrue($oauth->revokeToken());
  101. $this->assertEquals($refreshToken, $token);
  102. // Test with passed in token.
  103. $this->assertTrue($oauth->revokeToken($accessToken2));
  104. $this->assertEquals($accessToken2, $token);
  105. }
  106. public function testCreateAuthUrl()
  107. {
  108. $client = $this->getClient();
  109. $oauth = new Google_Auth_OAuth2($client);
  110. $client->setClientId('clientId1');
  111. $client->setClientSecret('clientSecret1');
  112. $client->setRedirectUri('http://localhost');
  113. $client->setDeveloperKey('devKey');
  114. $client->setAccessType('offline');
  115. $client->setApprovalPrompt('force');
  116. $client->setRequestVisibleActions(array('http://foo'));
  117. $client->setLoginHint("bob@example.org");
  118. $authUrl = $oauth->createAuthUrl("http://googleapis.com/scope/foo");
  119. $expected = "https://accounts.google.com/o/oauth2/auth"
  120. . "?response_type=code"
  121. . "&redirect_uri=http%3A%2F%2Flocalhost"
  122. . "&client_id=clientId1"
  123. . "&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo"
  124. . "&access_type=offline"
  125. . "&approval_prompt=force"
  126. . "&login_hint=bob%40example.org";
  127. $this->assertEquals($expected, $authUrl);
  128. // Again with a blank login hint (should remove all traces from authUrl)
  129. $client->setLoginHint("");
  130. $client->setHostedDomain("example.com");
  131. $client->setOpenidRealm("example.com");
  132. $client->setPrompt("select_account");
  133. $client->setIncludeGrantedScopes(true);
  134. $authUrl = $oauth->createAuthUrl("http://googleapis.com/scope/foo");
  135. $expected = "https://accounts.google.com/o/oauth2/auth"
  136. . "?response_type=code"
  137. . "&redirect_uri=http%3A%2F%2Flocalhost"
  138. . "&client_id=clientId1"
  139. . "&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo"
  140. . "&access_type=offline"
  141. . "&prompt=select_account"
  142. . "&hd=example.com"
  143. . "&openid.realm=example.com"
  144. . "&include_granted_scopes=true";
  145. $this->assertEquals($expected, $authUrl);
  146. }
  147. /**
  148. * Most of the logic for ID token validation is in AuthTest -
  149. * this is just a general check to ensure we verify a valid
  150. * id token if one exists.
  151. */
  152. public function testValidateIdToken()
  153. {
  154. if (!$this->checkToken()) {
  155. return;
  156. }
  157. $client = $this->getClient();
  158. $token = json_decode($client->getAccessToken());
  159. $segments = explode(".", $token->id_token);
  160. $this->assertEquals(3, count($segments));
  161. // Extract the client ID in this case as it wont be set on the test client.
  162. $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1]));
  163. $oauth = new Google_Auth_OAuth2($client);
  164. $ticket = $oauth->verifyIdToken($token->id_token, $data->aud);
  165. $this->assertInstanceOf(
  166. "Google_Auth_LoginTicket",
  167. $ticket
  168. );
  169. $this->assertTrue(strlen($ticket->getUserId()) > 0);
  170. // TODO(ianbarber): Need to be smart about testing/disabling the
  171. // caching for this test to make sense. Not sure how to do that
  172. // at the moment.
  173. $client = $this->getClient();
  174. $client->setIo(new Google_IO_Stream($client));
  175. $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1]));
  176. $oauth = new Google_Auth_OAuth2($client);
  177. $this->assertInstanceOf(
  178. "Google_Auth_LoginTicket",
  179. $oauth->verifyIdToken($token->id_token, $data->aud)
  180. );
  181. }
  182. /**
  183. * Test for revoking token when none is opened
  184. */
  185. public function testRevokeWhenNoTokenExists()
  186. {
  187. $client = new Google_Client();
  188. $this->assertFalse($client->revokeToken());
  189. }
  190. /**
  191. * Test that the ID token is properly refreshed.
  192. */
  193. public function testRefreshTokenSetsValues()
  194. {
  195. $client = new Google_Client();
  196. $response_data = json_encode(
  197. array(
  198. 'access_token' => "ACCESS_TOKEN",
  199. 'id_token' => "ID_TOKEN",
  200. 'expires_in' => "12345",
  201. )
  202. );
  203. $response = $this->getMock("Google_Http_Request", array(), array(''));
  204. $response->expects($this->any())
  205. ->method('getResponseHttpCode')
  206. ->will($this->returnValue(200));
  207. $response->expects($this->any())
  208. ->method('getResponseBody')
  209. ->will($this->returnValue($response_data));
  210. $io = $this->getMock("Google_IO_Stream", array(), array($client));
  211. $io->expects($this->any())
  212. ->method('makeRequest')
  213. ->will(
  214. $this->returnCallback(
  215. function ($request) use (&$token, $response) {
  216. $elements = $request->getPostBody();
  217. PHPUnit_Framework_TestCase::assertEquals(
  218. $elements['grant_type'],
  219. "refresh_token"
  220. );
  221. PHPUnit_Framework_TestCase::assertEquals(
  222. $elements['refresh_token'],
  223. "REFRESH_TOKEN"
  224. );
  225. return $response;
  226. }
  227. )
  228. );
  229. $client->setIo($io);
  230. $oauth = new Google_Auth_OAuth2($client);
  231. $oauth->refreshToken("REFRESH_TOKEN");
  232. $token = json_decode($oauth->getAccessToken(), true);
  233. $this->assertEquals($token['id_token'], "ID_TOKEN");
  234. }
  235. }