谷歌php客户端库loadServiceAccountJson破碎修复封闭



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添加到服务器auth json文件中的数据中,该文件从Developer Console/api &Auth/Credentials(您需要创建一个服务帐户)-将文件命名为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);

新的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>'));

我还在努力弄清楚我怎么能得到这个不需要冒充用户?

最新更新