refreshTokenWithAssertion Permission Denied

2020-07-18 02:28发布

问题:

I am trying to use google-api-client in PHP for a project. I got a "permission denied" response while at this statement:

$client->getAuth()->refreshTokenWithAssertion();

Google_IO_Exception, Message:Failed to connect to 74.125.193.84: Permission denied File: /home/www/blah.com/restful/libs/Google/IO/Curl.php Line:81 /home/www/blah.com/restful/libs/Google/IO/Abstract.php(125): Google_IO_Curl->executeRequest(Object(Google_Http_Request))

#1 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(326): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))

#2 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(306): Google_Auth_OAuth2->refreshTokenRequest(Array)

#3 /home/www/blah.com/restful/v2/index.php(122): Google_Auth_OAuth2->refreshTokenWithAssertion()

I checked all my credentials and they look correct, what could be the problem?

Thanks, John

code:

$client_id = '1234blahblahblah.apps.googleusercontent.com'; //Client ID
$service_account_name = '1234blahblah@developer.gserviceaccount.com'; //Email Address 
$key_file_location = 'blahblah-1234.p12'; //key.p12

$client = new Google_Client();
$client->setApplicationName("test");
$service = new Google_Service_Calendar($client);  
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);

$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/calendar'),
    $key
   );

print_r($cred);

$client->setAssertionCredentials($cred);

$client->setClientId($client_id);

if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
} 
$_SESSION['service_token'] = $client->getAccessToken(); 
echo $_SESSION['service_token'];
}

回答1:

Hi John I´ve the same problem and finally this works for me:

Before the lines:

if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
} 

I put a try catch and that returns me that I had a writtin permissions problem:

try {
  $client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
  var_dump($e->getMessage());
}

I could do 2 things:

1) Go to Google/src/Config.php and change line 94: 'directory' => sys_get_temp_dir() . '/Google_Client'and change the directory to save cache temp files

2) or like me, made a echo sys_get_temp_dir(); before the try catch and give a chmod 777 permission to that dir

This solution works for me, I hope also for you. Anyway made an try/catch waiting for the exception message



回答2:

See the service-account.php sample in the examples/ directory of the Google APIs Client Library for PHP on Github.com:

if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred); // set credentials there
}