You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Docs API 403权限错误:如何为Cloud Run使用的服务账户通过IAM分配Docs API的所有者或编辑器角色

Google Docs API 403权限错误:如何为Cloud Run使用的服务账户通过IAM分配Docs API的所有者或编辑器角色

问题重现的错误信息

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://docs.googleapis.com/v1/documents?alt=json returned "The caller does not have permission". Details: "The caller does not have permission">
Traceback (most recent call last):
  File "/app/book_editor/nodes.py", line 554, in create_and_share_book_doc
    doc = docs_service.documents().create(body={"title": book.book_title}).execute()
  File "/usr/local/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.10/site-packages/googleapiclient/http.py", line 938, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://docs.googleapis.com/v1/documents?alt=json returned "The caller does not have permission". Details: "The caller does not have permission">

问题背景

你当前的场景是:使用Google Docs API创建并编辑文档,服务部署在GCP Cloud Run(Docker镜像),绑定Compute Engine服务账户,已启用Docs API且配置了GOOGLE_APPLICATION_CREDENTIALS环境变量,服务账户邮箱与credentials.json一致,但遇到403权限错误。代码中使用的权限范围如下:

scope = [
  "https://www.googleapis.com/auth/documents",
  "https://www.googleapis.com/auth/drive",
  "https://spreadsheets.google.com/feeds",
  "https://www.googleapis.com/auth/drive.file",
]
creds, project_id = google.auth.default(scopes=scope)
docs_service = build("docs", "v1", credentials=creds, cache_discovery=False)
drive_service = build("drive", "v3", credentials=creds, cache_discovery=False)
doc = docs_service.documents().create(body={"title": book.book_title}).execute()

解决方案:为服务账户分配正确的IAM角色

你找不到单独的“Docs API Owner/Editor”角色是因为:Google Docs的创建、编辑权限是通过Google Drive IAM角色来管控的,而非独立的Docs API角色。以下是具体操作步骤:

步骤1:进入GCP IAM控制台

  1. 打开GCP控制台,导航到IAM与管理员 > IAM页面
  2. 页面顶部选择你部署Cloud Run的目标项目

步骤2:定位目标服务账户

在IAM列表中找到Cloud Run使用的Compute Engine服务账户(邮箱需与credentials.json完全一致),点击账户右侧的编辑图标(铅笔样式)

步骤3:添加适配的角色

点击添加另一个角色,在搜索框中选择以下合适的角色:

  • 若仅需创建Docs文档并管理自己创建的文档:选择Drive > Drive文件创建者
    这个角色允许服务账户创建新的Drive文件(包括Docs),且自动拥有所创建文件的所有权,满足你的创建+编辑需求
  • 若需要访问或编辑其他用户共享的Docs文档:选择Drive > Drive编辑器
  • 若需精细控制已有Docs的编辑权限:可额外添加Docs > 文档编辑器角色(注意:该角色无法单独用于创建文档,需搭配Drive角色)

步骤4:保存并等待权限生效

点击保存按钮后,等待1-2分钟让GCP IAM权限同步(权限生效可能有短暂延迟)

额外注意事项

  • 检查是否有IAM拒绝政策限制了该服务账户的权限
  • 确认Cloud Run服务确实在使用目标服务账户:进入Cloud Run服务详情的安全标签,查看“服务账户”配置是否正确
  • 你测试的其他项目服务账户能正常工作,大概率是因为该账户已被分配了Drive相关角色

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 11:28:03