0

I am trying to change the password for a user using Google Admin SDK and consuming Google Directory API.

Here is my code:

<?php
require_once __DIR__ . '/vendor/autoload.php';


define('APPLICATION_NAME', 'CRONDAQ');
define('CREDENTIALS_PATH', '/root/.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)
));

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);

$password = crypt ( "Password", $salt="IamSecretkey" );

$userObj = new Google_Service_Directory_User(
    array(
        'password' =>  $password
    )
);

try{
    $results = $service->users->update("danish@XXX.in", $userObj );
} catch(Error $ex) {
print_r($ex->getMessage());
}

echo "<pre>";
print_r($results);

Here is the error that i am getting:

PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } }

  • Try checking the [scopes](https://developers.google.com/admin-sdk/directory/v1/guides/authorizing) you are using if it allows you to update the user's password. You could also try [using service accounts with Admin SDK for domain-wide delegation.](https://developers.google.com/admin-sdk/directory/v1/guides/delegation) as stated in the related SO [post](http://stackoverflow.com/a/22836835/5995040) and properly impersonate one of those users to access the Admin SDK Directory API. Hope this helps. – Mr.Rebot Jan 29 '17 at 14:45
  • I think you should pay close attention at the comments. `// If modifying these scopes, delete your previously saved credentials // at ~/.credentials/admin-directory_v1-php-quickstart.json`. Or else you can also try setting up your own [authentication flow](https://developers.google.com/api-client-library/php/auth/web-app) instead of using the one from the quickstart.php – Morfinismo Jan 30 '17 at 20:32

1 Answers1

0

"Insufficient Permission" could indicate that your account is trying to change the password of another user and your account does not have the prerequisite roles needed to make such changes.

   $client = new Google_Client();
   ...
   ...
   $client->setScopes(SCOPES);
   $client->setSubject($impersonate);

... where $impersonate is "adminWithRolesToMakeChanges@XXX.in". The roles are set in the admin console. Could this be the issue?

Jay Fowler
  • 65
  • 6