Google API 服务帐户模拟是指使用一个服务帐户来代表另一个用户(通常是域管理员)执行操作的技术。这在企业环境中很常见,当需要以某个用户的身份批量执行操作时使用。
错误表现:
Google_Service_Exception: Not Authorized to access this resource/api
原因:
解决方案:
$client = new Google_Client();
$client->setAuthConfig('service-account.json');
$client->setScopes([Google_Service_Directory::ADMIN_DIRECTORY_USER]);
$client->setSubject('admin@yourdomain.com'); // 设置要模拟的用户
错误表现:
Google_Service_Exception: Delegation denied for [service account email]
原因:
解决方案:
错误表现:
Google_Service_Exception: Invalid Credentials
原因:
解决方案:
// 自动刷新令牌的示例
$client = new Google_Client();
$client->setAuthConfig('service-account.json');
$client->setScopes([Google_Service_Directory::ADMIN_DIRECTORY_USER]);
$client->setSubject('admin@yourdomain.com');
$client->setAccessType('offline'); // 允许刷新令牌
// 检查令牌是否过期
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithAssertion();
}
require_once 'vendor/autoload.php';
try {
$client = new Google_Client();
$client->setAuthConfig('service-account.json');
$client->setScopes([
Google_Service_Directory::ADMIN_DIRECTORY_USER,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP
]);
$client->setSubject('admin@yourdomain.com');
// 设置访问类型为离线,允许刷新令牌
$client->setAccessType('offline');
// 检查令牌是否过期
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithAssertion();
}
// 使用Directory API
$service = new Google_Service_Directory($client);
// 示例:获取用户列表
$users = $service->users->listUsers([
'domain' => 'yourdomain.com',
'maxResults' => 10
]);
foreach ($users->getUsers() as $user) {
echo $user->getPrimaryEmail() . "\n";
}
} catch (Google_Service_Exception $e) {
echo "Google Service Exception: " . $e->getMessage();
// 可以记录更详细的错误信息
// error_log(json_encode($e->getErrors()));
} catch (Exception $e) {
echo "General Exception: " . $e->getMessage();
}
通过正确配置服务帐户模拟,可以安全高效地完成这些任务而无需直接使用用户凭证。
没有搜到相关的文章