Reputation: 43
Need help about google admin sdk. I m newbie on google admin sdk. So i am stuck on its showing error while authorizing like code 403: Not Authorized to access this resource/api. Here is my Code.
<?php
include_once '../vendor/autoload.php';
include_once "base.php";
session_start();
echo pageHeader("Service Account Access");
/************************************************
Make an API request authenticated with a service
account.
************************************************/
$client = new Google_Client();
$client->setAuthConfig('client_secret1.json');
$client->setApplicationName("automate user");
$client->setScopes(['https://www.googleapis.com/auth/admin.directory.user']);
$client->setSubject('admin@XXXXX');
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
//$auth_url = $client->createAuthUrl();
//header('Location: '.filter_var($auth_url, FILTER_SANITIZE_URL));
if(isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
if ($credentials_file = checkServiceAccountCredentialsFile()) {
// set the location manually
$client->setAuthConfig('client_secret1.json');
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS=automate user.json')) {
// use the application default credentials
$client->useApplicationDefaultCredentials();
} else {
echo missingServiceAccountDetailsWarning();
return;
}
$dir = new Google_Service_Directory($client);
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();
$results = $dir->users->get('[email protected]');
if($results) {
echo "Name : ".$results->name->fullName."";
} else{
echo " User doesn't exist : ".$email;
}
}
else {
$redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. '/google/oauth.php';
header('Location: '.filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
pageFooter(__FILE__); ?>
Actually i want o create an user through google api. Please tell me anybody what's i do wrong ? please help me
Upvotes: 1
Views: 894
Reputation: 6729
You can create a user through Users: insert. There is a Try it now to test if you have entered correct/valid data.
Here is a sample code from quickstart to help your progress.
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
For further information about this error, see this SO post.
you need to enable domain-wide delegation for your service account, and then have the service account impersonate a domain admin when it makes the request:
Upvotes: 1