Google php api authentication exception

398 views Asked by At

I'm trying to authenticate google service account using Outh2 but keep getting this error -

Exception - Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }'

I have followed every instruction at https://developers.google.com/api-client-library/php/auth/service-accounts I also did authorize the service account from google Admin console but still no luck. Can anyone please suggest if there is anything wrong in the code below -

$client_email = [email protected]';
        $private_key = file_get_contents('private_key_file_location.p12');
        $scopes = array('https://spreadsheets.google.com/feeds');
        $user_to_impersonate = '[email protected]';
        $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, 
                                                            $private_key, 'notasecret',
                                                           'http://oauth.net/grant_type/jwt/1.0/bearer',
                                                           $user_to_impersonate);

        $client = new Google_Client();

        $client->setApplicationName('Portal Assessment Module');
        $client->setAccessType('offline');

        $client->setAssertionCredentials($credentials);
        if ($client->getAuth()->isAccessTokenExpired()) {
            $client->getAuth()->refreshTokenWithAssertion($credentials);    /* Exception 
is being triggered here */    
}

Thank you.

2

There are 2 answers

0
Sandeep On BEST ANSWER

Finally figured it out, had to make sure that $user_to_impersonate is same as the $client_email and also that email address has edit access to the spreadsheets.

$user_to_impersonate = $client_email
1
gun On

Try this

require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');

define('SCOPES', implode(' ', array(Google_Service_Appsactivity::DRIVE)));

$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    SCOPES,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired())
{
    $client->getAuth()->refreshTokenWithAssertion();
}

print_r($client->getAccessToken());