【问题标题】:Google php client library loadServiceAccountJson broken - fix enclosed谷歌 php 客户端库 loadServiceAccountJson 损坏 - 随附修复
【发布时间】:2015-07-24 16:46:54
【问题描述】:

php 库loadServiceAccountJson 中的新函数不允许在Google_Auth_AssertionCredentials 创建者中设置sub,所以总是给授权失败。我们如何更新库?

以下说明将允许一个有效的查询,在我的例子中是 Admin SDK Directory API:

首先,将src/Google/Client.php中的php库函数loadServiceAccountJson更新为:

  public function loadServiceAccountJson($jsonLocation, $scopes)
  {
    $data = json_decode(file_get_contents($jsonLocation));
    if (isset($data->type) && $data->type == 'service_account') {
      // Service Account format.
      $cred = new Google_Auth_AssertionCredentials(
          $data->client_email,
          $scopes,
          $data->private_key,
          'notasecret',
          'http://oauth.net/grant_type/jwt/1.0/bearer',
          $data->sub
      );
      return $cred;
    } else {
      throw new Google_Exception("Invalid service account JSON file.");
    }
  }

然后,将值 sub 添加到服务器身份验证 json 文件中的数据,该文件是从开发人员控制台/API 和身份验证/凭据下载的(您需要创建一个服务帐户) - 将文件命名为 serverauth.json

{
  "private_key_id": "removed",
  "private_key": "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n",
  "client_email": "removed",
  "client_id": "removed",
  "redirect_uris":[your urls here],
  "type": "service_account",
  "sub": "valid.user@google.domain.com"
}

现在,获得授权:

$credentials = $client->loadServiceAccountJson('serverauth.json',"https://www.googleapis.com/auth/admin.directory.user.readonly");
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion();
}

最后,创建一个 Directory 实例并查询它:

$service = new Google_Service_Directory($client);
$optParams = array(
        'domain' => 'google.domain.com',
        'orderBy' => 'email',
        'viewType' => 'domain_public',
        'query' => "givenName:'Joe' familyName:'Schmoe Jr'"
);
$results = $service->users->listUsers($optParams);
$users = $results->getUsers();

print_r($users);

【问题讨论】:

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


    【解决方案1】:

    新的 Google API 现在有点不同了:

    $client = new Google_Client();
    $client->setApplicationName("YourAppName");
    $client->setAuthConfig(<JSON-Config-File-Location>);
    $client->setScopes(array("https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.group.readonly"));
    $client->setSubject(<User-Email-To-Impersonate>);
    
    $service = new Google_Service_Directory($client);
    $results = $service->users->listUsers(array('domain' => '<your-domain-name>'));
    

    我仍在试图弄清楚如何在无需模拟用户的情况下获得此功能?

    【讨论】:

    • 除非您当前的服务帐户对您需要的范围具有权限,否则您可能无法在不充当域内的用户的情况下执行此操作。 (域管理员可以为您设置,但默认情况下您可能不会拥有它。)我不知道有一个新库 - 我去看看。
    猜你喜欢
    • 2018-03-26
    • 2017-10-28
    • 2017-03-14
    • 1970-01-01
    • 2016-03-21
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    相关资源
    最近更新 更多