google admin sdk未授权访问此资源/ api php

时间:2017-12-03 10:52:00

标签: php google-oauth google-admin-sdk

需要关于google admin sdk的帮助。我是google admin sdk上的新手。因此,在授权代码403:Not Notized访问此资源/ api时,我仍然坚持显示错误。这是我的代码。

<?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('xxxxx@xxx.org');

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

其实我想通过谷歌api创建一个用户。请告诉我任何人我做错了什么?请帮帮我

1 个答案:

答案 0 :(得分:0)

您可以通过Users: insert创建用户。如果您输入了正确/有效的数据,则需要Try it now进行测试。

这是帮助您取得进步的sample code from quickstart

<?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());
  }
}

有关此错误的详细信息,请参阅此SO post

  

您需要为您的服务启用domain-wide delegation   帐户,然后让服务帐户模拟域管理员   当它提出请求时: