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

调用Google Chat API出现401未授权错误的原因排查

Google Chat API 401 未授权错误的可能原因

我按照Google Chat API的spaces.get接口文档编写了代码,但执行后返回不符合预期的401未授权错误。

我的代码实现

function myFunction() {
  var url = 'https://chat.googleapis.com/v1/spaces/AAAA*******'
  var options = {
    method: 'GET',
    headers: {"Authorization": 'Bearer ' + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response)
}

清单中的权限配置

"oauthScopes": [
  "https://www.googleapis.com/auth/script.external_request",
  "https://www.googleapis.com/auth/chat.spaces"
]

返回的错误响应

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "method": "google.chat.v1.ChatService.GetSpace",
          "service": "chat.googleapis.com"
        }
      }
    ]
  }
}

补充说明:我最初写错了权限,但修正后问题仍然存在,现已更新上述代码。


可能导致401错误的原因:

  • OAuth令牌未正确传递:检查ScriptApp.getOAuthToken()是否返回有效令牌。可以先通过Logger.log(ScriptApp.getOAuthToken())打印令牌,确认其不为空且格式正确(Bearer后需加空格再跟令牌字符串)。
  • 权限范围未生效:即使清单中配置了权限,Google Apps Script可能需要重新授权才能加载新权限。尝试重新部署脚本,或手动触发授权流程(运行脚本时在弹出的授权窗口中重新确认权限)。
  • 令牌权限不匹配:确认chat.spaces权限是否覆盖spaces.get接口的访问需求,部分场景下可能需要更具体的chat.spaces.readonly权限(需对照官方权限说明)。
  • 关联GCP项目配置异常:如果脚本绑定了自定义Google Cloud项目,需确认该项目已启用Google Chat API,且OAuth同意屏幕配置正确(已添加所需权限,外部用户使用需通过审核)。
  • 令牌过期或失效:虽然ScriptApp.getOAuthToken()会自动刷新令牌,但极端情况可能出现未刷新的问题,可尝试重启脚本或重新发起授权。
  • 请求头格式错误:检查Authorization头的拼写、大小写是否正确,避免因格式问题导致服务端无法识别令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:22:43