Google Apps脚本script.run - 即使在发送Oauth令牌时也会出现意外情况401

问题描述 投票:0回答:1

我正在尝试使用Google Apps脚本API方法scripts.run运行Google Apps脚本。但是,我收到403错误,并出现以下错误消息:

{
  "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"
  }
}

以下是我发送的POST请求的标头:

authorization: Bearer my-oauth-token
Content-Type: application/json
Origin: http://localhost:5000
Referer: http://localhost:5000/static/test.html
User-Agent: Mozilla/5.0...

我发送请求到https://script.googleapis.com/v1/scripts/my_script_id:run?key=my_api_key

有任何想法吗?我尝试过搜索示例,但是当我需要使用REST API时,我得到的就是谷歌apis客户端库。我确信我的oauth令牌是正确的,因为我向其他Google apis提出了相同的请求。

这是我目前的流程:

  1. 将用户重定向到oauth url,并获取交换代码。我的重定向网址是
"https://accounts.google.com/o/oauth2/v2/auth?"
        "scope=https://www.googleapis.com/auth/drive&"
        "state=%s&"
        "redirect_uri=redirect_uri&"
        "client_id=id&"
        "response_type=code&"
        "access_type=offline&"
        "prompt=consent"
  1. 刷新令牌的交换代码
  2. 使用刷新令牌获取oAuth访问令牌。我向https://www.googleapis.com/oauth2/v4/token发送POST请求来执行此操作。
  3. 我使用访问令牌从用户的谷歌幻灯片获取缩略图。此请求成功。
  4. 我发送执行Google Apps脚本的请求。以下是此请求的汇总代码:
xhr.open("POST", "https://script.googleapis.com/v1/scripts/id:run", true);
xhr.setRequestHeader("authorization", "Bearer " + oauth_token);
xhr.onload = function() { // do stuff }
xhr.onerror = function() { // print error }
xhr.send(JSON.stringify({
   "function": "run",
    "parameters": [
       id1,
       id2
    ]
}));

这给了我401错误。我也收到消息“显示临时标题”。我调查了这一点,它似乎与我的问题没有关系.enter image description here

这是我尝试运行的脚本:

function doGet(e) {
  if(!(e.parameter.source && e.parameter.destination)) {
    throw new Error("Not all parameters specified");
  }
  copySlides(e.parameter.source, e.parameter.destination);
}

function copySlides(sourceId, destinationId) {
  var src = SlidesApp.openById(sourceId);
  var dest =  SlidesApp.openById(destinationId);

  src.getSlides().forEach(function(slide, index) {
      dest.appendSlide(slide);
  });
  return ContentService.createTextOutput("Done Copying Slides");
}
google-apps-script google-api google-oauth http-status-code-401 google-apps-script-api
1个回答
0
投票

事实证明我错过了额外的oAuth范围,因为我的脚本使用了Google SlidesApp。添加https://www.googleapis.com/auth/presentations范围固定。

© www.soinside.com 2019 - 2024. All rights reserved.