我在Google API控制台中有一个APP。它启用了Admin SDK,还有Marketplace SDK。我已将其注册为服务帐户,并且我有密钥文件等。当我尝试从某个域获取用户时,它总是向我显示一条消息 - “调用GET https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.com时出错:(403)Not授权访问此资源/ api“。我的代码就是:
$client = new Google_Client();
$client->setApplicationName("Client_User_Feed");
$key = file_get_contents('/path/to/key/key-file-privatekey.p12');
$cred = new Google_Auth_AssertionCredentials(
'{code}@developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/admin.directory.user'),
$key
);
$client->setAssertionCredentials($cred);
$service = new Google_Service_Directory($client);
$users = $service->users->listUsers(array('domain' => 'mydomain.com'));
我该如何解决这个问题?
答案 0 :(得分:0)
您需要使用以下内容模拟管理员用户:
$adminUser = 'admin@domain.com';
$cred->sub = $adminUser;
获取用户ID的示例代码:
$client_id = '{code}.apps.googleusercontent.com'; //Client ID from Developers Console
$service_account_name = '{code}@developer.gserviceaccount.com'; //Email Address from Developers Console
$key_file_location = '{path}{file}.p12'; //Path to the P12 key downloaded from Developers Console
$impersonateUser = 'standarduser@domain.com'; //The user's account we are fetching information from
try {
$client = new Google_Client(); //Instantiate the Google Client
$client->setApplicationName("ApplicationName");
$adminService = new Google_Service_Directory($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials( //Instantiate the Auth class
$service_account_name,
array('https://www.googleapis.com/auth/admin.directory.user'), //Set the scope
$key
);
$adminUser = 'admin@domain.com';
$cred->sub = $adminUser; //The sub function of Auth lets us impersonate a user so that our service account ($client_id) can act on the user's behalf
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$getUser = getUserId($adminService, $impersonateUser);
$impersonateUser = $getUser['primaryEmail'];
if (isset($impersonateUser) && !empty($impersonateUser)) {
$_SESSION['gmailUserID'] = $impersonateUser;
}
//echo $_SESSION['gmailUserID'] . "<br />";
} catch (Exception $e) {
LogErr($e);
}
function getUserId($adminService, $impersonateUser) {
try {
$userId = $adminService->users->get($impersonateUser);
return $userId;
} catch (Exception $e) {
LogErr($e);
}
}