Reputation: 51
I'm having an issue getting auth code in the same pop-up window rather than redirecting a user to another page in google auth. I'm trying to access the google analytics API and for that, I'm using auth 2. What do I need to change in order to get the auth code in the same google prompt? FYI: I'm using WordPress.
Edits: I have created the new auth desktop client and now I can set the redirect URI as mentioned above, and using that I'm able to create the auth code and access token. However, I'm getting the ACCESS_TOKEN_SCOPE_INSUFFICIENT error when calling the admin API. I have checked the admin and data API and both are enabled in my google console. The same thing works fine when I use the web application auth client but our requirement is to use the installed plugin as that provides the auth code within the prompt.
Below is the process of creating access_token which works fine:
if (isset($_POST["save_code"]) && isset($_POST["access_code"])) {
$authCode = $_POST["access_code"];
$client = new Google_Client();
$client->setClientId('***');
$client->setClientSecret('***');
$client->setDeveloperKey('***');
// $client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setScopes([
'https://www.googleapis.com/auth/analytics',
'openid',
'https://www.googleapis.com/auth/analytics.readonly'
]);
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->authenticate($authCode);
$access_token = $client->getAccessToken();
var_dump($access_token);
// echo "<pre>";
// print_r($access_token);
// exit;
}
$url = http_build_query(
array(
'next' => 'http://myproject.local.com/wp-admin/admin.php?page=analytify-settings',
'scope' => 'https://www.googleapis.com/auth/analytics',
'response_type' => 'code',
'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
'client_id' => '***'
)
);
?>
<form action="<?php echo str_replace('%7E', '~', $_SERVER['REQUEST_URI']); ?>" method="post" name="settings_form" id="settings_form">
<table width="1004" class="form-table">
<tbody>
<tr>
<th width="115">Authentication:</th>
<td width="877">
<a target="_blank" href="javascript:void(0);" onclick="window.open('https://accounts.google.com/o/oauth2/auth?<?php echo $url ?>', 'activate', 'width=700,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0');">Click here to Authenticate</a>
</td>
</tr>
<tr>
<th>Your Access Code:</th>
<td>
<input type="text" name="access_code" value="" style="width:450px;" />
</td>
</tr>
<tr>
<th></th>
<td>
<p class="submit">
<input type="submit" class="button-primary" value="Save Changes" name="save_code" />
</p>
</td>
</tr>
</tbody>
</table>
</form>
Creating the admin client:
$admin_client = new AnalyticsAdminServiceClient([
'credentials' => Google\ApiCore\CredentialsWrapper::build([
'scopes' => [
'https://www.googleapis.com/auth/analytics',
'openid',
'https://www.googleapis.com/auth/analytics.readonly',
],
'keyFile' => [
'type' => 'authorized_user',
'client_id' => '***',
'client_secret' => '***',
'refresh_token' => 'my refresh token'
],
]),
]);
$accounts = $this->admin_client->listAccountSummaries();
The above code gives this error:
Fatal error: Uncaught Google\ApiCore\ApiException: { "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "errorInfoMetadata": { "method": "google.analytics.admin.v1alpha.AnalyticsAdminService.ListAccountSummaries", "service": "analyticsadmin.googleapis.com" }, "message": "Request had insufficient authentication scopes.", "code": 7, "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "metadata": { "method": "google.analytics.admin.v1alpha.AnalyticsAdminService.ListAccountSummaries", "service": "analyticsadmin.googleapis.com" } } ] } thrown in pathToProject\vendor\google\gax\src\ApiException.php on line 260
Upvotes: 0
Views: 8028
Reputation: 116908
Lets start with ACCESS_TOKEN_SCOPE_INSUFFICIENT
If you check the documentation account summaries list it requires one of the following scopes
So the error message means that the access token you are sending does was not authorized with one of those scopes.
My guess is that you authorized it with https://www.googleapis.com/auth/analytics and then added readonly after and did not remove the old tokens. You need to authorize the app again with the proper scope.
Due to the removal of oob you can not use this
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
Please check (Making Google OAuth interactions safer by using more secure OAuth flows). TBH you shouldnt need to add it but if you want to try https://127.0.0.1
Have a look at my sample
Simple How to Integrate php with Google analytics admin api.
function getClient()
{
$client = new Client();
$client->setApplicationName('Google analytics admin beta Oauth2');
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setAuthConfig(getenv('GOOGLE_APPLICATION_CREDENTIALS'));
$client->setAccessType('offline');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'tokenAdmin.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
Upvotes: 0