如何使用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
相关产品推荐
相关产品推荐

