【问题标题】:Creating a file with Google Drive API using a Service Account doesn't render file on authorized user account's GD使用服务帐户使用 Google Drive API 创建文件不会在授权用户帐户的 GD 上呈现文件
【发布时间】:2020-12-03 19:42:02
【问题描述】:

我目前正在尝试创建一个文件,并使用 Google 提供的服务帐户身份验证方法将其上传到 Google Drive 帐户(因为它在最终产品中都是服务器端的,我不希望用户必须授权访问,所以没有 OAuth per-say)。

我目前能够连接到服务帐户并上传文件,但是当我浏览我的 Google 云端硬盘时文件没有显示。

(我能够使用 OAuth 方法让它工作(上传和渲染);我会在上传之前手动授权应用程序,所以我很确定代码可以正常工作)

另外,我知道它的另一种工作方式是,上传完成后,我会返回一个文件 ID。如果我去“https://drive.google.com/file/d/FILE_ID/view?usp=sharing”,我会遇到“需要授权”。

在创建服务帐户时我应该做些什么,以便我的 Gmail 帐户可以访问文件?


有关信息,这是我连接到 API(服务器端)的方式:

<?php
$client = new Google_Client();

if ($this->oauth_credentials = $this->getServiceAccountCredentialsFile()) :
    $client->setAuthConfig($this->oauth_credentials);
endif;

if ($this->warning != null) :
    echo $this->warning;
    return;
endif;

$client->setApplicationName("Test Google Drive Service Account");
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$service = new Google_Service_Drive($client);

define("TESTFILE", ABSPATH.'testfile-small.txt');
if (!file_exists(TESTFILE)) {
    $fh = fopen(TESTFILE, 'w');
    fseek($fh, 1024 * 1024);
    fwrite($fh, "!", 1);
    fclose($fh);
}

$file = new Google_Service_Drive_DriveFile();
$result = $service->files->create(
    $file,
    array(
        'data' => file_get_contents(TESTFILE),
        'mimeType' => 'application/octet-stream',
        'uploadType' => 'media'
    )
);
echo '<pre>'; var_dump($result->id); echo '</pre>';

【问题讨论】:

标签: google-api google-drive-api google-oauth google-api-php-client


【解决方案1】:

如果您希望服务帐号在不征得其他用户同意的情况下代表其他用户行事,您必须:通过 G Suite 管理员,为服务帐号启用 Domain-Wide-Delegation。

否则,服务帐户需要至少征求用户一次同意,并存储访问令牌和刷新令牌,因为令牌过期时,它可以无限期地使用 Google 服务器刷新它。

更多信息在这里:https://developers.google.com/admin-sdk/directory/v1/guides/delegation

【讨论】:

    【解决方案2】:

    你有四个选择...

    1. 不要使用服务帐户。只需为用户帐户存储一个刷新令牌。见How do I authorise an app (web or installed) without user intervention?。服务帐户是服务器访问的唯一选项是一个神话。
    2. 使用服务帐户写入已由您的用户帐户共享到服务帐户的文件夹
    3. 使用服务帐户写入您的服务帐户与您的用户帐户共享的文件夹
    4. 使用 G-Suite 域中的服务帐户来模拟用户帐户

    选项 1. 是最简单的,2 和 3 仅在谁拥有文件以及根据谁的配额计算文件方面有所不同。 4 仅与 G-Suite 相关

    【讨论】:

    • 感谢您的信息,我一定会检查其他方法以使其有效;我不知道服务帐户不是这样做的唯一方法。
    • @pinoyyid 你好,你能提供链接在哪里可以找到关于选项 4 的详细信息吗?
    • @Nurs123 此 repo 使用模拟技术来更改所有权。您只是想用创建文件替换更改所有权
    • @pinoyyid 您能否分享一些有关如何执行选项 2 或 3 的详细信息(或链接)?
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多