Dima Dima - 1 month ago 8
PHP Question

PHP - Google Admin SDK - Authentication with Service Accounts "Not Authorized to access this resource/api"

I'm using the library google/google-api-php-client and I'm creating an authentication with service accounts.

I have created the service account in https://console.developers.google.com/ and I added the domain-wide authority to my service account.

But i return i request the following:

Google_Service_Exception in REST.php line 118:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not Authorized to access this resource/api"
}
],
"code": 403,
"message": "Not Authorized to access this resource/api"
}
}


My function:

$client = new \Google_Client();

$credentials_file = base_path() . '/service-account.json';

if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
$client->setAuthConfig($credentials_file);
}

$client->setApplicationName("app-name");
$client->setScopes([
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
]);

$service = new \Google_Service_Directory($client);

$userKey = 'user@domain.com';

$results = $service->users->get($userKey);

var_dump($results);


If I try here is working.
https://developers.google.com/admin-sdk/directory/v1/reference/users/get#auth

Answer

I could solve the problem. I lacked set subject with my user admin on the domain:

$client->setSubject("admin@yourdomain.com");

Result:

$client = new \Google_Client();

$credentials_file = base_path() . '/service-account.json';

if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
    $client->setAuthConfig($credentials_file);
}

$client->setApplicationName("app-name");
$client->setSubject("admin@yourdomain.com");
$client->setScopes([
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
]);

$service = new \Google_Service_Directory($client);

$userKey = 'user@domain.com';

$results = $service->users->get($userKey);

var_dump($results);
Comments