使用服务帐户上传时,如何解决 Google 驱动器的存储空间超出问题

How to fix the storage exceeded issue for Google Drive when uploading using Service Accounts

如果您正在使用 Google Apps for Work(也称为 G-Suite)并通过云端硬盘 API 将文件上传到您的 Google 云端硬盘,您最终会发现自己错误消息如下所示:

Error: The user's Drive storage quota has been exceeded.

阅读下文了解发生这种情况的原因以及解决方法。

背景:

Google 驱动器 API 被授权使用 "service accounts",而不是常规的 "human users"。 Google 目前无法增加服务帐户的 15GB 限制,也没有购买额外 space 的机制。消耗完标准 space 分配后,您将无法上传任何其他文件。

Human/regular G-Suite 用户也可以获得标准的 15GB,但只需几分钱就可以通过简单的选项将其增加到 100GB 或更多。

那么,如何根据人工帐户而非服务帐户的存储配额上传文件,以便您可以拥有任意多的 space?其实很简单!只是没有很好的记录...

解法:

此解决方案是将您的服务帐户配置为模拟 人类帐户。这意味着您仍然使用服务帐户对驱动器 API 进行身份验证,但服务帐户已获得代表人类帐户的授权,并且存储 space 将从该用户的配额中分配。

准备:这很重要。 Carefully review the instructions here to make sure your service account is set up correctly for impersonation. Any deviation from this will give you random errors that will frustrate you and waste time. The service account needs to have DwD (domain-wide-delegation) enabled in the Google IAM Console AND it needs to be permitted to access the Drive scope in the API client access page of the Google Admin site.

现在您的服务帐户已正确设置,要模拟普通帐户,您只需在创建 JWT 客户端时指定人类帐户电子邮件地址即可。

在 NodeJS 中它看起来像这样(注意最后一个参数):

let jwtClient = new GoogleApi.auth.JWT( service_account_email, null, private_key, ['https://www.googleapis.com/auth/drive'], 'impersonated_user@mydomain.com');

其他语言请参考官方Google文档如何模拟用户。

当您的云端硬盘 API 脚本现在上传文件时,这些文件将归该普通用户所有,并且 space 将从他们的配额中分配。增加它是微不足道的,可以由任何管理员或通过联系 G-Suite 支持来完成。