【问题标题】:Google PHP Client API - Error 400 Admin SDKGoogle PHP 客户端 API - 错误 400 管理 SDK
【发布时间】:2020-08-05 00:15:31
【问题描述】:


我正在尝试在 google GSuite for Education 上获取与用户关联的组。 我已经开始按照教程列出与关联相关的所有用户,但我得到:错误 400 -“消息”:“无效输入。
到目前为止,我已经创建了一个带有服务帐户的项目,因为我需要没有用户交互,因为必须自动完成获取。 之后,我将帐户设置为启用 G Suite 域范围委派,并将其放在具有 https://www.googleapis.com/auth/admin.directory.group.readonlyhttps://www.googleapis.com/auth/admin.directory.user.readonly 域的授权 API 客户端中,但是当我运行代码时,出现上述错误
代码如下:

<?php
  require_once './google-api/vendor/autoload.php';
  putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/Culturalia.json');

  function getGoogleClient() {
    return getServiceAccountClient();
  }

  function getServiceAccountClient() {
    try {
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
  }

  $client = getGoogleClient();
  $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());
    }
  }
?>

但我猜这更有可能是我在某处丢失的授权,任何帮助将不胜感激。

【问题讨论】:

    标签: php google-authentication google-admin-sdk google-client


    【解决方案1】:

    问题:

    您可能已向服务帐户授予域范围的委派(仔细检查您是否已使用 this guide 完成此操作),但您尚未使用此委派模拟任何帐户在域中。这就是你缺少的部分。

    授予域范围委派的目的是让服务帐户能够代表您域中的任何帐户访问资源。但是,您需要指定要模拟的帐户;否则,您不会冒充任何人,并且服务帐户的行为就像您根本没有授予域范围内的委派一样

    由于服务帐户在技术上不是域的一部分,因此在尝试列出域用户时会出错。

    解决办法:

    要模拟一个帐户,您需要在设置client 时指定其电子邮件地址,如下所示:

    $user = "email-address@your-domain";
    $client->setSubject($user);
    

    参考:

    【讨论】:

    • 你让我很开心,我完全错过了那部分,谢谢!
    • @AlbertoCassinari 不客气。另外,请记住,您可以accept 回答您认为有帮助的答案。这很有用,因为这个社区依靠它与其他用户分享知识。
    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2016-09-24
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2013-01-19
    • 2016-06-07
    相关资源
    最近更新 更多