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

如何使用Python(通过服务账号)触发Apps Script Web App的doGet()?

解决服务账号访问受限Apps Script Web App的401错误

以下是排查和解决401认证错误的关键步骤:

1. 修正Web App部署权限

  • 重新部署Web App时,将**“谁可以访问此应用”设置为“仅限我的组织内的任何人”**,确保组织内用户(包括服务账号模拟的用户)有权访问。
  • 执行权限选择**“以访问者身份执行”**,避免因身份模拟额外增加权限配置复杂度。

2. 开启服务账号的域范围委派

  • 登录Google Admin控制台,找到目标服务账号,启用域范围委派功能。
  • 进入Admin控制台的安全 > API控制 > 域范围委派,添加服务账号的客户端ID,并配置所需权限范围:
    • 至少添加https://www.googleapis.com/auth/script.external_request和https://www.googleapis.com/auth/userinfo.email,确保服务账号能模拟组织用户获取有效身份凭证。

3. 代码中添加用户模拟逻辑

服务账号默认使用自身身份,无法访问组织受限资源,需模拟组织内有效用户身份:

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
import requests

SERVICE_ACCOUNT_FILE = r'C:\Users\USER\Documents\fga-openrpa-sa.json'
SCOPES = [
    'https://www.googleapis.com/auth/script.external_request',
    'https://www.googleapis.com/auth/userinfo.email'
]

# 添加subject参数,指定组织内有权访问Web App的用户邮箱
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES,
    subject='valid-user@your-domain.com'
)
    
authed_session = AuthorizedSession(credentials)

# 确保URL为正确的部署地址,替换为实际的domain和deployment-id
url = 'https://script.google.com/a/macros/your-domain.com/s/actual-deployment-id/exec?page=something'

try:
    response = authed_session.get(url)
    response.raise_for_status()
    print("Response status code:", response.status_code)
    print("Response content:", response.text)
except requests.exceptions.RequestException as e:
    print("An error occurred:", e)

4. 验证Web App地址正确性

确认URL格式为https://script.google.com/a/macros/[your-domain]/s/[deployment-id]/exec,其中deployment-id是Web App部署时生成的唯一ID,而非自定义路径。

内容的提问来源于stack exchange,提问作者Lemuel Dingal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:12:38