【发布时间】:2015-02-18 15:40:26
【问题描述】:
我正在学习 Drive API 并且到目前为止已经阅读了所有这些文档。我只是尝试进行经过身份验证的调用以列出驱动器中的文件。
这是一个不需要用户身份验证的内部应用程序,我只需要访问我们公司的驱动器。所以“服务帐户”听起来很合适。
这是我到目前为止所做的
- 在 Google Developer Console 中创建了一个应用
- 同时启用 Drive API 和 Drive SDK
- 下载并存储了我的 p12 密钥
- 在此处指定的高级设置下的 Google App Admin 中添加了我的客户端 ID 和驱动器权限https://developers.google.com/accounts/docs/OAuth2ServiceAccount
这是我列出文件的代码
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
require_once 'google-api-php-client/autoload.php';
$client_id = '...'; //Client ID
$service_account_name = '...'; //Email Address
$key_file_location = '...'; //key.p12
$client = new Google_Client();
$client->setApplicationName("...");
$service = new Google_Service_Drive($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.file'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$results = $service->files->listFiles();
debug($results);
?>
我的结果是一个名为“如何开始使用云端硬盘”的文件。所以很明显,它没有通过我的帐户进行身份验证来显示我的驱动器文件。
知道如何将此服务帐户与我的驱动器帐户相关联,以便我可以获取文件列表吗?
【问题讨论】:
-
尝试跟踪 http 流量以查看发生了什么。另外仅供参考,如果您还指定驱动器,则不需要 drive.file 范围,因为驱动器是 drive.file 的超集。
-
我在找什么?我知道我想要访问驱动器的用户的设置不正确。
-
这是一般性评论。每当我遇到 Drive 或 auth 问题时,一旦我通过观察底层 http 消除了 SDK,通常更容易诊断。我一直通过组织对我想要访问的特定云端硬盘帐户的直接访问来避免使用服务帐户。这篇文章展示了如何使用该技术stackoverflow.com/questions/19766912/…
标签: php google-drive-api