gpt4 book ai didi

impersonation - 使用服务帐户模拟 Google 用户

转载 作者:行者123 更新时间:2023-12-04 15:45:49 24 4
gpt4 key购买 nike

我正在使用 google-api-php-client 0.6.1,我想知道有没有办法用服务帐户模拟具体用户?我的应用程序需要在其谷歌驱动器中存储一些文件。因此,我决定使用用户服务帐户和 .p12 key 进行身份验证。效果很好,但所有文件都存储在服务帐户中,所以我无法管理它们。我希望将文档存储在某个帐户(用于创建 api 项目和服务帐户本身)。我试图使用此代码:

$KEY_FILE = <p12 key file path>;
$key = file_get_contents($KEY_FILE);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/drive'),
$key);
$auth->prn = '<certainuser@gmail.com>';
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);

但我收到“刷新 OAuth2 token 时出错,消息:'{“错误”:“access_denied”}'”

最佳答案

不要使用 $auth->prn,使用 $auth->sub。这对我有用:

// Create a new google client.  We need this for all API access.
$client = new Google_Client();
$client->setApplicationName("Google Group Test");

$client_id = '...';
$service_account_name = '...';
$key_file_location = '...';

if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);

// https://www.googleapis.com/auth/admin.directory.group,
// https://www.googleapis.com/auth/admin.directory.group.readonly,
// https://www.googleapis.com/auth/admin.directory.group.member,
// https://www.googleapis.com/auth/admin.directory.group.member.readonly,
// https://www.googleapis.com/auth/apps.groups.settings,
// https://www.googleapis.com/auth/books
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array(
Google_Service_Groupssettings::APPS_GROUPS_SETTINGS,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,

Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER,
Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER_READONLY,

Google_Service_Books::BOOKS,
),
$key,
'notasecret'
);
//
// Very important step: the service account must also declare the
// identity (via email address) of a user with admin priviledges that
// it would like to masquerade as.
//
// See: http://stackoverflow.com/questions/22772725/trouble-making-authenticated-calls-to-google-api-via-oauth
//
$cred->sub = '...';
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

关于impersonation - 使用服务帐户模拟 Google 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15241127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com