PHP Google API service accounts - php

I am currently struggling to get access to the google api when impersonating a user.
I can connect as that user however I am getting an error where I am presented with an error:
"error": {
"errors": [
{
"domain": "global",
"reason": "appNotAuthorizedToFile",
"message": "The user has not granted the app <app id> write access to the file <file id>",
"locationType": "header",
"location": "Authorization"
}
],
}
The recommended resolution is to use google Picker and get the user to allow my app to access this file. However as I am using a service account with domain wide delegation and g-suite enabled I thought this wasn't necessary.
my current php code is:
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setAuthConfig($credentials);
$client->addScope($scopes);
$client->setClientId($key);
$client->useApplicationDefaultCredentials();
$client->setSubject($userTobe);
$client->setAccessType('offline');
I am using putenv to push my service_account.json into my file. I followed the quick start as it suggested. I have enabled all the required scopes in the security console. If I specify getRefreshTokenwithAssertion() i can get an access_token starting with ya29. however this still presents the error above.
I am currently at a loss on where to go from here. Any help would be greatly appreciated.

Which scopes are you using? Please ensure you are setting the drive auth scope in your application: https://www.googleapis.com/auth/drive (Google_service_Drive::DRIVE)

Has the client and scopes been authorized in the admin console?
admin console => security => Advanced settings => manage API client access

Related

Use google drive API to change the owner of a file created with an account service

I used an service account to upload files to a shared folder in google drive.
After some time I discovered that files owned by service account consumed the service's account drive storage (my bad) and now I have run out drive space for the service account .
I already delegated domain-wide authority to the service account so new files will be owned by me and use my personal storage quota.
Did this: Delegating domain-wide authority to the service account
and this How to use the API Key for Google Drive API from PHP via the google/apiclient
To avoid errors and confusion in the future I'd like to change the owner of older files. I keep getting this error:
{ "error": {
"code": 400,
"message": "Bad Request. User message: \"You can't change the owner of this item.\"",
"errors": [ {
"message": "Bad Request. User message: \"You can't change the owner of this item.\"",
"domain": "global",
"reason": "invalidSharingRequest"
} ]
}
}
Here's my code using PHP Client
$client = new Google_Client();
$client->setApplicationName('My Name');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig($my_credentials);
$client->setAccessType('offline');
//$client->setSubject('my_personal_account');
$service = new Google_Service_Drive($client);
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress('my_personal_account');
$newPermission->setType('user');
$newPermission->setRole('owner');
$service->permissions->create(
$fileId,
$newPermission,
array("fields" => "id", "transferOwnership" => true)
);
I've got the same error with or without setSubject in the client. I've tried using
$newPermission->setRole('writer');
$newPermission->setPendingOwner(true);
but it didn't work.
Transfering the file ownership can only be done between accounts from the same domain. The error occurs because the service account and your account don't belong to the same domain.
If you have access to a Shared Drive and are able to add users with add files privileges, add the service account and make it move the files to the Shared Drive.
Related
transfer file ownership in Google Drive API
Unable to transfer ownership of file from service account to google drive user
Other related
Google Drive API ownership of files uploaded from service account
Google Drive API - Transfer ownership from Service Account

Google Server-to-Server OAuth2 PHP example not working

I am following this example to get server-to-server access working between my PHP application and Google Cloud API's,
https://developers.google.com/api-client-library/php/auth/service-accounts. In particular, I need to access the Drive API.
When I run the application though I get the following error:
Google_Service_Exception : {
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
}
Here's what I have done:
Created a GCP project
Added a service account to the project, with domain wide delegation, and a set of keys
Enabled the Google Drive API in the project
In my G Suite account, under 'Manage API client access', I have added the Client ID of my service account, with the permission of https://www.googleapis.com/auth/drive
Have I missed a step?
Here's my code:
putenv('GOOGLE_APPLICATION_CREDENTIALS=my_storage/secure/my-app-service-account.json');
$client = new \Google_Client();
$client->setScopes(\Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->useApplicationDefaultCredentials();
$client->setSubject('my_email#my_domain.com');
$drive = new \Google_Service_Drive($client);
echo $drive->about->get();
The example does not include the setScopes() call, however I was getting a scope-related error without it. (The example is not based on the Drive API, so perhaps it's not required in that case?)
UPDATE: In the IAM settings for the GCP, I added the email address of the service account as a Project Owner, but that made no difference.
I found the problem.
In the setScopes() call above, the value passed needs to be the same as the value given when setting up the client in G Suite, in this case https://www.googleapis.com/auth/drive

Google Service Account: androidpublisher Insufficient permissions to perform the requested operation

I know this question has been asked for several times here but none of the solution worked for me.
Following are the steps I followed to create a service account:
Logged in to Google Play Console account.
Then navigated to Settings > API Access from the left panel.
Scrolled down to Service Accounts section and clicked on Create Service Account.
Followed the instruction mentioned on dialog opened.
While creating service account on Google API Console selected Service account Permissions as Project > Owner
Created key and downloaded in json format.
Now came back to Google Play Console and clicked on Grant Access to grant permission as Administrator.
Now I am using this service account to validate In App Purchases on server but I am getting this error:
{
"errors": [
{
"domain": "androidpublisher",
"reason": "permissionDenied",
"message": "The current user has insufficient permissions to perform the requested operation."
}
],
"code": 401,
"message": "The current user has insufficient permissions to perform the requested operation."
}
}
I am using this php lib and service account method to verify purchases.

Google API PHP error 500

I'm using google vision API in one of my PHP script.
Script works well when I'm executing it through the terminal:
php /var/www/html/my_script.php
But when I want to execute it from my browser I'm getting an error 500:
PHP Fatal error: Uncaught
Google\Cloud\Core\Exception\ServiceException: {\n "error": {\n
"code": 401,\n "message": "Request had invalid authentication
credentials. Expected OAuth 2 access token, login cookie or other
valid authentication credential. See
https://developers.google.com/identity/sign-in/web/devconsole-project.",\n
"status": "UNAUTHENTICATED"\n }\n}\n
I don't get why the error message suggests me to use OAuth 2, I don't need my user to log to his google account.
My code is the following:
namespace Google\Cloud\Vision\VisionClient;
require('vendor/autoload.php');
use Google\Cloud\Vision\VisionClient;
$projectId = 'my_project_id';
$path = 'https://tedconfblog.files.wordpress.com/2012/08/back-to-school.jpg';
$vision = new VisionClient([
'projectId' => $projectId,
]);
$image = $vision->image(file_get_contents($path), ['WEB_DETECTION']);
$annotation = $vision->annotate($image);
$web = $annotation->web();
Generally speaking, you will need to provide a service account keyfile when constructing a Google Cloud client. The exception to this is if you're running on Compute Engine, or if you have Application Default Credentials setup. Since you're seeing authentication errors, neither of those appear to be the case.
To obtain a service account and keyfile, check out the documentation.
Once you have created a service account and downloaded the json keyfile, you can provide it to the client library constructor:
<?php
use Google\Cloud\Vision\VisionClient;
$vision = new VisionClient([
'projectId' => $projectId,
'keyFilePath' => '/path/to/keyfile.json'
]);
Once you provide a valid keyfile, you should be able to make authenticated requests to the Vision API.
To avoid this step, you can setup Application Default Credentials on your server or computer.

Using Google OAuth 2.0 for Server to Server Applications PHP

I've been following this guide perfectly https://developers.google.com/api-client-library/php/auth/service-accounts in an attempt to get any little bit of information back from google, yet I keep getting a 403 Insufficient Permission.
I have created a service account, and it has given me a little json file with a private key, project ID, a client email and client ID, and lots of other nifty stuff that I cannot share here on stack overflow.
I then delegated domain wide authority to the service account to speciifc API scopes. https://www.googleapis.com/auth/analytics.readonly I did this through Google Apps domain's admin console.
I then prepared to make an authorized api call with this little bit of php.
<?php
require_once __DIR__ . '/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
$user_to_impersonate = 'my_real_email#companyname.com';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/Users/alexfallenstedt/Desktop/Code/sticky-dash/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->setSubject($user_to_impersonate);
$sqladmin = new Google_Service_SQLAdmin($client);
$response = $sqladmin->instances->listInstances('examinable-example-123')->getItems();
echo json_encode($response) . '\n';
?>
I run this php file in console, and I keep getting this error.
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
I am lost. My whole team is lost. We've gone through this multiple times. How can we set up server to server communication to fetch our google analytics reporting api data?
I ended up forgetting the beta version, and instead referred to v3 of two-legged OAuth. https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php

Categories