403 尽管范围正确,但在 gspread python 中使用 GCP 服务帐户凭据创建电子表格时出错

问题描述 投票:0回答:1

尽管为我的服务帐户设置了我认为正确的身份验证范围,但在尝试使用 Python 中的 gspread 库创建 Google 电子表格时,我遇到了 403 错误。错误详细信息是:

{
  "code": 403,
  "message": "Request had insufficient authentication scopes.",
  "errors": [
    {
      "message": "Insufficient Permission",
      "domain": "global",
      "reason": "insufficientPermissions"
    }
  ],
  "status": "PERMISSION_DENIED",
  "details": [
    {
      "@type": "type.googleapis.com/google.rpc.ErrorInfo",
      "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
      "domain": "googleapis.com",
      "metadata": {
        "service": "drive.googleapis.com",
        "method": "google.apps.drive.v3.DriveFiles.Create"
      }
    }
  ]
}

我正在使用附加到虚拟机的服务帐户来验证请求。下面是触发错误的Python代码片段:

from google.auth import default
import gspread
credentials, _ = default(scopes=["https://www.googleapis.com/auth/drive"])
gc = gspread.authorize(credentials)
sheet_name = 'test_service_account'
sh = gc.create(sheet_name)

这是我迄今为止尝试过的:

  • 我已经检查了与 Google 云端硬盘相关的角色(例如 Roles/drive.file 或 角色/驱动器)在 IAM 控制台中,但没有找到它们列出 服务帐户。
  • 我已经明确设置了必要的范围 (https://www.googleapis.com/auth/drive) 初始化默认值时 服务帐户凭据。
  • 我已确保为我的项目启用了 Google Drive API。我 有另一个具有看似相同角色的服务帐户,即 能够毫无问题地创建电子表格。

如何解决此权限错误?是否有不同的方法来为我的服务帐户分配必要的角色,或者还有其他我可能会忽略的事情吗?

python google-cloud-platform google-drive-api service-accounts gspread
1个回答
0
投票

我同意 DazWilin 先生的观点,并发表他的评论作为答案。

IIRC Google Workspace 服务(包括云端硬盘)不在 Google Cloud IAM 覆盖范围内,因此不存在

roles/drive.file
等角色。您必须改为使用 OAuth 范围。不过,文档建议您必须先将服务帐号的电子邮件地址添加到 Google Workspace 文档(包括表格)中,Python 库才能访问它。这是有道理的(尽管我以前从未见过这样做),因为除非您使用域范围委派,否则服务帐户不允许访问用户工作区数据。

因此,您无法使用该库创建工作表,因为工作表需要存在才能向其添加共享凭据。

© www.soinside.com 2019 - 2024. All rights reserved.