使用有效OAuth令牌向Google Apps Script Web应用发POST请求时出现401未经授权错误

3 投票
1 回答
79 浏览
提问于 2025-04-14 18:18

我正在尝试用一个Python脚本向一个Google Apps Script的网页应用发送一个POST请求。用浏览器访问这个网页应用的URL时,GET请求可以正常工作,但用Python发送POST请求时却出现了401未授权的错误。

认证过程是这样的:

from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']
CLIENT_SECRETS_FILE = 'client_secret.json'

flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:80/')
credentials = flow.run_local_server(port=80)

headers = {
    'Authorization': f'Bearer {credentials.token}',
    'Content-Type': 'application/json',
}

# Checking token validity
if credentials.valid:
    print("Token is valid.")
else:
    print("Token is not valid.")

# Checking if the token has expired
if credentials.expired:
    print("Token has expired.")
else:
    print("Token is still valid.")

print("Scopes granted to the token:", credentials.scopes)
print("Access token:", credentials.token)


    try:
       response = requests.post(url, headers=headers, json={"text": "hello from python with OAuth"})
       response.text
       response.raise_for_status()  # 400 or 500 Error
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error occurred: {err}")  # HTTP Error
    except Exception as err:
        print(f"An error occurred: {err}")  # Other Error 

而appsscript.json的设置如下:

{
  "timeZone": "Asia/Seoul",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "DOMAIN"
  }
}

令牌是有效的,授权的范围也没有问题。根据Google Cloud控制台,用户拥有所有者权限,并且Apps Script API已经启用。

尽管有这些设置和条件,我还是不明白为什么POST请求会失败。网页应用的doPost函数是用来处理JSON类型的POST数据的。我希望能得到一些建议,看看我可能遗漏了什么。

谢谢。

我尝试过的:

我用Python脚本向Google Apps Script的网页应用发送了一个POST请求。我使用了OAuth 2.0进行认证,在请求头中包含了访问令牌,并发送了请求。Google Apps Script中的doPost函数被设置为接收和处理JSON数据。

我期待的结果:

在成功完成认证过程并获得有效的访问令牌后,我期待网页应用能够接收到POST请求并做出相应的回应。

实际发生的情况:

虽然通过浏览器用GET请求访问网页应用是正常的,但通过Python脚本发送POST请求却出现了401未授权的错误。因此,网页应用没有处理这个请求。

1 个回答

1

关于状态码 401,它的意思是 HTTP 401 Unauthorized 响应状态码表示客户端请求未完成,因为缺少对请求资源的有效身份验证凭据。 参考链接

为了用访问令牌请求网络应用,目前需要包含 Drive API 的范围。我猜当我看到你展示的脚本时,这可能是你当前问题的原因。那么,下面的修改怎么样呢?

从:

SCOPES = ['openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

到:

SCOPES = ["https://www.googleapis.com/auth/drive"]

或者

SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]

或者,如果你需要使用 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy' 这些范围,请按以下方式修改。

SCOPES = ["https://www.googleapis.com/auth/drive", 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

或者

SCOPES = ["https://www.googleapis.com/auth/drive.readonly", 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

注意:

  • 很遗憾,我对你的 Google Apps Script 没有任何信息。所以,这个回答是针对你展示的 Python 脚本的修改。并且假设你的 Google Apps Script 是正常工作的。请对此保持谨慎。

参考:

撰写回答