PHP - Google Admin SDK -未经授权访问此资源/api的服务帐户的身份验证


PHP - Google Admin SDK - Authentication with Service Accounts "Not Authorized to access this resource/api"

我正在使用库google/google-api-php-client,我正在创建一个服务帐户的身份验证。

我已经在https://console.developers.google.com/中创建了服务帐户,并为我的服务帐户添加了域范围的权限。

但是我返回i请求以下内容:

Google_Service_Exception in REST.php line 118:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Not Authorized to access this resource/api"
}
],
"code": 403,
"message": "Not Authorized to access this resource/api"
}
}

我的函数:

$client = new 'Google_Client();
$credentials_file = base_path() . '/service-account.json';
if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
    $client->setAuthConfig($credentials_file);
}
$client->setApplicationName("app-name");
$client->setScopes([
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
]);
$service = new 'Google_Service_Directory($client);
$userKey = 'user@domain.com';
$results = $service->users->get($userKey);
var_dump($results);

如果我尝试这里是工作。https://developers.google.com/admin-sdk/directory/v1/reference/users/get auth

我可以解决这个问题。我的用户admin在域上缺少set subject:
$client->setSubject("admin@yourdomain.com");
结果:

$client = new 'Google_Client();
$credentials_file = base_path() . '/service-account.json';
if ($credentials_file = $this->checkServiceAccountCredentialsFile($credentials_file)) {
    $client->setAuthConfig($credentials_file);
}
$client->setApplicationName("app-name");
$client->setSubject("admin@yourdomain.com");
$client->setScopes([
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
]);
$service = new 'Google_Service_Directory($client);
$userKey = 'user@domain.com';
$results = $service->users->get($userKey);
var_dump($results);