/** * A generic wrapper for cURL that abstracts away common requirements * and issues around using the GME API. * * Params: * Google_OAuth2 $oauthClient - An OAuth2 Client object. * string $url - The complete URL to call include query string params. * array $options - An additional cURL options to pass through. * * Notably: * - Content-type: application/json for POST requests * - Catching rate limit exceeded errors */ function curl_wrapper(Google_Auth_OAuth2 $oauthClient, $url, $options = array()) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt_array($ch, $options); $headers = array('Authorization: Bearer ' . $oauthClient->getAccessToken()); // Google accepts POST data as JSON only - no form-encoded input if (isset($options[CURLOPT_POST]) && $options[CURLOPT_POST] == true) { $headers[] = "Content-Type: application/json"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = json_decode(curl_exec($ch)); if (!in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), array(200, 204))) { // You'll want to handle errors... } if (isset($response->error) && $response->error->errors[0]->reason === "rateLimitExceeded") { // If you've can have multiple simultaneous clients you'll probably want to catch // and handle rate limit errors. So sleep for an arbitrary period... usleep(1000000); // ...and try again } curl_close($ch); return $response; }
/** * Most of the logic for ID token validation is in AuthTest - * this is just a general check to ensure we verify a valid * id token if one exists. */ public function testValidateIdToken() { if (!$this->checkToken()) { return; } $client = $this->getClient(); $token = json_decode($client->getAccessToken()); $segments = explode(".", $token->id_token); $this->assertEquals(3, count($segments)); // Extract the client ID in this case as it wont be set on the test client. $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1])); $oauth = new Google_Auth_OAuth2($client); $this->assertInstanceOf("Google_Auth_LoginTicket", $oauth->verifyIdToken($token->id_token, $data->aud)); // TODO(ianbarber): Need to be smart about testing/disabling the // caching for this test to make sense. Not sure how to do that // at the moment. $client = $this->getClient(); $client->setIo(new Google_IO_Stream($client)); $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1])); $oauth = new Google_Auth_OAuth2($client); $this->assertInstanceOf("Google_Auth_LoginTicket", $oauth->verifyIdToken($token->id_token, $data->aud)); }
/** * @param string $key_location * @param string $email_address */ function __construct($key_location, $email_address) { $this->email_address = $email_address; $this->key_file_location = $key_location; $this->client = new Google_Client(); $key = file_get_contents($this->key_file_location); $cred = new Google_Auth_AssertionCredentials($this->email_address, Google_Service_Bigquery::BIGQUERY, $key); $this->client->setAssertionCredentials($cred); //setup proxy if neccesary /*$io = new Google_IO_Curl($this->client); $curlOptions = array(); $curlOptions[CURLOPT_PROXY] = "http://proxy.local"; $curlOptions[CURLOPT_PROXYPORT] = "8080"; $io->setOptions($curlOptions); $this->client->setIo($io);*/ if ($this->client->getAuth()->isAccessTokenExpired() || $this->client->getAccessToken() == NULL || $this->client->getAccessToken() == '') { $auth = new Google_Auth_OAuth2($this->client); $auth->refreshTokenWithAssertion($cred); $token = $auth->getAccessToken(); $this->client->setAccessToken($token); } // Instantiate a new BigQuery Client $this->bigqueryService = new Google_Service_Bigquery($this->client); }
/** * Verify a JWT that was signed with your own certificates. * * @param $id_token string The JWT token * @param $cert_location array of certificates * @param $audience string the expected consumer of the token * @param $issuer string the expected issuer, defaults to Google * @param [$max_expiry] the max lifetime of a token, defaults to MAX_TOKEN_LIFETIME_SECS * @return mixed token information if valid, false if not */ public function verifySignedJwt($id_token, $cert_location, $audience, $issuer, $max_expiry = null) { $auth = new Google_Auth_OAuth2($this); $certs = $auth->retrieveCertsFromLocation($cert_location); return $auth->verifySignedJwtWithCerts($id_token, $certs, $audience, $issuer, $max_expiry); }
/** * Test that the ID token is properly refreshed. */ public function testRefreshTokenSetsValues() { $client = new Google_Client(); $response_data = json_encode(array('access_token' => "ACCESS_TOKEN", 'id_token' => "ID_TOKEN", 'expires_in' => "12345")); $response = $this->getMock("Google_Http_Request", array(), array('')); $response->expects($this->any())->method('getResponseHttpCode')->will($this->returnValue(200)); $response->expects($this->any())->method('getResponseBody')->will($this->returnValue($response_data)); $io = $this->getMock("Google_IO_Stream", array(), array($client)); $io->expects($this->any())->method('makeRequest')->will($this->returnCallback(function ($request) use(&$token, $response) { $elements = $request->getPostBody(); PHPUnit_Framework_TestCase::assertEquals($elements['grant_type'], "refresh_token"); PHPUnit_Framework_TestCase::assertEquals($elements['refresh_token'], "REFRESH_TOKEN"); return $response; })); $client->setIo($io); $oauth = new Google_Auth_OAuth2($client); $oauth->refreshToken("REFRESH_TOKEN"); $token = json_decode($oauth->getAccessToken(), true); $this->assertEquals($token['id_token'], "ID_TOKEN"); }
private function checkIdTokenFailure($id_token, $msg) { $certs = $this->getSignonCerts(); $oauth2 = new Google_Auth_OAuth2($this->getClient()); try { $oauth2->verifySignedJwtWithCerts($id_token, $certs, "client_id"); $this->fail("Should have thrown for {$id_token}"); } catch (Google_Auth_Exception $e) { $this->assertContains($msg, $e->getMessage()); } }
public function testVerifySignedJwtWithMultipleIssuers() { $id_token = $this->makeSignedJwt(array("iss" => "system.gserviceaccount.com", "aud" => "client_id", "sub" => self::USER_ID, "iat" => time(), "exp" => time() + 3600)); $certs = $this->getSignonCerts(); $oauth2 = new Google_Auth_OAuth2($this->getClient()); $ticket = $oauth2->verifySignedJwtWithCerts($id_token, $certs, "client_id", array('system.gserviceaccount.com', 'https://system.gserviceaccount.com')); $this->assertEquals(self::USER_ID, $ticket->getUserId()); // Check that payload and envelope got filled in. $attributes = $ticket->getAttributes(); $this->assertEquals("JWT", $attributes["envelope"]["typ"]); $this->assertEquals("client_id", $attributes["payload"]["aud"]); }
public function updateFromGoogleAccount() { $client = GoogleSessionController::getClient(); $oauth2 = new \Google_Auth_OAuth2($client); if ($this->google_token && $oauth2->isAccessTokenExpired() == false) { $oauth2->refreshToken($this->google_token); $client->setAccessToken($oauth2->getAccessToken()); $oauth2 = new \Google_Service_Oauth2($client); $google_user = $oauth2->userinfo->get(); // update the photo GoogleSessionController::saveGoogleProfileImage($google_user, $this); // other things later.. return true; } return false; }
private function authGoogle() { $_TokenGoogle = sha1(openssl_random_pseudo_bytes(1024)); $clientGoogle = new \Google_Auth_OAuth2($this->client); $urlAuth = $clientGoogle->createAuthUrl(\Google_Service_Oauth2::USERINFO_EMAIL . ' ' . \Google_Service_Oauth2::USERINFO_PROFILE . ' ' . \Google_Service_Calendar::CALENDAR . ' ' . \Google_Service_Drive::DRIVE); //\Session::put('_TokenGoogle',$_TokenGoogle); //\Session::save(); //$value = \Session::get('_TokenGoogle'); //$urlAuth="https://accounts.google.com/o/oauth2/auth?client_id=".$cfgGoogleApi['client_id']."&response_type=code&scope=profile&redirect_uri=".$cfgGoogleApi['redirect_uris'][0]."&login_hint=jose.hdez.bta@gmail.com&state=".$state; header('Location: ' . $urlAuth); exit; }
/** * @param \Google_Auth_AssertionCredentials $creds */ public function setAssertionCredentials(\Google_Auth_AssertionCredentials $creds) { $this->creds = $creds; parent::setAssertionCredentials($creds); }
public static function getGoogleUser(&$user) { if ($user->hasToken()) { $client = GoogleSessionController::getClient(); $auth = new Google_Auth_OAuth2($client); $auth->refreshToken($user->getToken()); $token = $auth->getAccessToken(); $client->setAccessToken($auth->getAccessToken()); $oauth2 = new Google_Service_Oauth2($client); $google_user = $oauth2->userinfo->get(); // save the latest token // $user->google_token = $auth->getRefreshToken(); // $user->save(); return $google_user; } else { $url = GoogleSessionController::generateGoogleLoginURL(['approval_prompt' => 'force', 'state' => 'refresh_token']); return Redirect::to($url); } }