我正在使用google-api-php-client 0.6.1,我想知道有没有办法模拟具体服务帐户的用户?我的应用程序需要在其谷歌硬盘中存储一些文件。所以,我决定使用服务帐户和.p12密钥 - 验证。它运行良好,但所有文件都存储在服务帐户中,因此我无法管理它们。我希望将文档存储在特定帐户(用于创建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令牌时出错,消息:'{”错误“:”access_denied“}'”
答案 0 :(得分:1)
请勿使用$ auth-&gt; prn,请使用$ auth-&gt; 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();