Google Apps Admin SDK Directory API 403 in PHP - php

I'm getting
Error calling GET https://www.googleapis.com/admin/directory/v1/users/email#example.com.com: (403) Not Authorized to access this resource/api
when running
$client = new Google_Client();
$client->setClientId(GOOGLEAPPS_CLIENT_ID);
$client->setApplicationName(SITE_NAME);
$key = file_get_contents(APPLICATION_PATH . 'googleapps-privatekey.p12');
$assertion = new Google_AssertionCredentials(
GOOGLEAPPS_EMAIL_ADDRESS, // the service account name
array('https://www.googleapis.com/auth/admin.directory.user'), // see https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
$key);
$client->setAssertionCredentials($assertion);
$service = new Google_DirectoryService($client);
$user = $service->users->get('email#example.com');
I followed the instructions https://developers.google.com/admin-sdk/directory/v1/guides/prerequisites
and ticked Enable API Access. I used the Google APIs console https://code.google.com/apis/console to generate a Service Account key and got that working OK.
https://groups.google.com/forum/#!msg/google-api-php-client/LM-mwmuZe7I/IA_K5v1R1UMJ
I used the Google PHP library and followed the instructions https://code.google.com/p/google-api-php-client/wiki/OAuth2?hl=no#Service_Accounts to try and get service accounts working. Debugging into their code: I'm authorising fine and getting a fresh Access token as expected https://developers.google.com/accounts/docs/OAuth2ServiceAccount.
I can't figure out why I'm getting the "Not Authorized to access this resource/api" message when everything I have read says I've switched it all on OK. Any ideas?

Just got it working. You need to include the user email of the admin so oAuth authorizes you for that user. Try
$assertion = new Google_AssertionCredentials(
GOOGLEAPPS_EMAIL_ADDRESS, // the service account name
array('https://www.googleapis.com/auth/admin.directory.user'), // see https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
$key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'admin_user#email.com'
);
Also after that you need to authorize the client_id for the scope you are requesting from Admin console->Security->Advanced Settings->Authentication->Manage OAuth Client access

I was having a similar problem. I'm using the .NET libraries. The [DriveService][1] example was missing a parameter when creating the provider: ServiceAccountUser, which appears to have to be the email address of an ADMIN. I missed that it was an admin and was getting:
Not Authorized to access this resource/api [403]
as soon as I switched it to an admin account, it worked. I'm afraid I don't speak PHP but I hope this helps.

If you get an error
Class 'Google_AssertionCredentials' not found
you are using the newer libraries, and Google_AssertionCredentials is now Google_Auth_AssertionCredentials.
See:
https://github.com/google/google-api-php-client/blob/master/src/Google/Auth/AssertionCredentials.php

Did you grant the service account access to the given scopes within your Control Panel? See the instructions in the Drive SDK and substitute in the Admin SDK scopes as needed.

Related

Service Account Domain Delegation unauthorized_client

I am trying to use service account with domain delegation so I can automate some tasks of google classroom via cron. For this I need service account with domain delegation.
I am working and struggling in it for 3 days. I have properly read documentation so many times. You can imagine the 3 days research. Now I am getting exhaust and finally come here in the hope.
I am using php library provided by google for google classroom.
https://github.com/googleapis/google-api-php-client
I am getting this error
Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
Which means in google documentation enter image description here
I tried that several times but still getting this errror.
Here is my php code
require_once plugin_dir_path(__FILE__).'../../xf-google-classroom/vendor/autoload.php';
$this->scopes = [
Google_Service_Classroom::CLASSROOM_COURSES,
//Google_Service_Classroom::CLASSROOM_ROSTERS,
//Google_Service_Classroom::CLASSROOM_COURSES_READONLY,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_ME,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_ME_READONLY,
//Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS,
Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY,
//Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS,
];
$this->credentials = plugin_dir_path(__FILE__) . '/sufi-new-2.json';
//$this->redirect_uri = site_url( 'wp-admin/admin.php?page=bp-groups' );
$this->client = new Google_Client();
//$this->client->useApplicationDefaultCredentials();
$jsonKey = [
"type"=> "service_account",
"project_id"=> "edufix-upgraded",
"client_email"=> "newsufyan#edufix-upgraded.iam.gserviceaccount.com",
"client_id"=> "115746479435703189142",
"auth_uri"=> "https://accounts.google.com/o/oauth2/auth",
"token_uri"=> "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url"=> "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url"=> "https://www.googleapis.com/robot/v1/metadata/x509/newsufyan%40edufix-upgraded.iam.gserviceaccount.com"
];
$this->client->setAuthConfig( $jsonKey );
$this->client->setSubject('clases#krugerschool.edu.ec');
//$this->client->setRedirectUri( $this->redirect_uri );
$this->client->addScope( $this->scopes );
$this->client->setAccessType( 'offline' );
Let me tell you that my OAuth2 authentication with conscent screen application is working good on frontend for users. I am not able to run my cron scripts because of this domain delegation.
Also my OAuth Consent screen is in test mode and I have added test users in it. And working good with users on frontend with consent screen.
Also I always generate new key after any new changes and deploy that new credentials as well everytime. I tried to remove and add again with client id and proper scopes and domain delegation again and again but not working.
Also I have added that my administrator account in service account and grant access to owner. But not not worked.
Kindly help
I am trying to solve my problem and expecting a poper solution

Get user login access token to use youtube API

I am using youtube API for scheduling live events for user in my application.
Once the user logged in my application i need to logged in the same user to our business google account(One google account for all user) without giving login credentials. and to get access token for scheduling the live events.
Is it possible to login the user into google account without giving login credentials(User will not feel he is login to another account).
Is it feasible with PHP?.Please give one example to get access token for youtube API access.
I used the following code for getting access token but service account can't access the youtube service.
My code for getting access token using service account:
<?php
require_once 'Google/autoload.php';
session_start();
$client_id = '395540674667-p64tdfqdsfsdfdsf#dsfd.com';
$Email_address = '54564-drgfdg1#developer.gserviceaccount.com';
$key_file_location = 'Youtube API-5czxczxc86.p12';
$client = new Google_Client();
$client->setApplicationName("Youtube API");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes = array('https://www.googleapis.com/auth/sqlservice.admin','https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/youtube');
$cred = new Google_Auth_AssertionCredentials($Email_address,
$scopes,
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//print_r($client);
echo $client->getAccessToken();
?>
I am expecting the answer is something like this.Any one please help
you example about Youtube api, first:
select credentials to your api project from here:
https://console.cloud.google.com/home/dashboard?project= with your project
also you need to have the api enable because google told us "Some APIs are enabled automatically."
when you select:
https://console.cloud.google.com/apis/api/youtube/ with Go to Credentials you have some option into modal window this will help
also.
the php code seem to be ok but also I think you will change after you learn more about Credentials settings.

AdSense Management API - Missing required parameter: redirect_uri With Service Account

I am getting the following Error when trying to connect with the AdSense Management API Example:
Missing required parameter: redirect_uri
I am using a service Account, because my Server handles all the interaction between the adSense api. The user is not involved. Here is my PHP Code:
$client = new Google_Client();
$client->setApplicationName("PeopleHelpingPeople"); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_Auth_AssertionCredentials(
"...",
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('client_data.json') // keyfile you downloaded
));
$client->setScopes(array(
'https://www.googleapis.com/auth/analytics.readonly'
));
$client->setClientId("..."); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// Create service.
$service = new Google_Service_AdSense($client);
Why am I getting this Error?
If you are trying to use a ServiceAccount from the developers console, the kind of account that gives you a p12 file, those will not work with Adsense.
Take a look at the note on this page https://developers.google.com/adsense/management/getting_started
$client->setRedirectUri() may get you past this error but it wont solve your ultimate issue

{ "error" : "invalid_grant" } error with Google Directory API PHP Client SDK

So I am trying all day already and I just can't seem to correctly authenticate to the google API. This is what I did to set up a connection so far:
I first created a service account for my application
Then I added that service account in the third party client access settings on the admin page for our Google Apps domain. I added the scopes for users and groups
I generated a new Client ID for web applications
I downloaded the .p12 file, the secret JSON file for my web Client ID and stored them locally
So I think that's all I need to succesfully authenticate.. I then used the following code to set everything up:
$this->client = new Google_Client();
$this->client->setAuthConfigFile(STORAGE_PATH.'client_secrets.json');
$this->client->addScope(static::$scopes);
$cred = new Google_Auth_AssertionCredentials(
static::$service_account_email,
static::$scopes,
file_get_contents(STORAGE_PATH.'TRICS-key.p12'));
$cred->sub = static::$delegated_admin;
$this->client->setAssertionCredentials($cred);
$this->directory_service = new Google_Service_Directory($this->client);
Does someone know if I am forgetting something?
Oops. I was a fool. I accidentally used the email of the Web Client instead of the service account email. :') The rest of the code seems to function as it should.

Connecting to the Google Sites API as a "Service Account"

I am trying to read a feed from a Google Sites account (Google apps).
I don't need my app to require every user to login so i created my ClientID as a "Service Account" in the "Google API console".
I have added this Client ID and the scope (https://sites.google.com/feeds/) to the "Mange API client access" page in my google apps control panel.
I connect using the code below, all constants are defined in my code with the right values.
// api dependencies
require_once(GOOGLE_API_PATH);
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName(GOOGLE_API_NAME);
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
GOOGLE_API_EMAIL,
array(GOOGLE_API_SCOPE),
file_get_contents(GOOGLE_API_PK)
));
$client->setClientId(GOOGLE_API_CLIENTID);
// create service
$req = new Google_HttpRequest("https://sites.google.com/feeds/content/<herismydomainname.com>/intranet");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode($val->getResponseBody());
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
The response i get is "Not authorized to access this feed "
When i try to get this feed in the OAuth2.0 playground logging in using my google apps account i get the expected response.
What am i overlooking here?
Service accounts and Google Sites can't be used together currently. Google Apps provides a consumer secret that can be used to access data across your domain as Two-Legged OAuth within OAuth 1.0a.
Check out http://support.google.com/a/bin/answer.py?hl=en&answer=162105 for how to configure your Apps account, and the sample code at https://developers.google.com/gdata/docs/auth/oauth#2LeggedOAuth.

Categories