首页 > 解决方案 > 如何从浏览器将访问令牌传递给 Google 应用脚本 rest API 调用?

问题描述

我有一个调用已部署为可执行脚本的应用程序脚本的函数。

我在反应应用程序中使用正确的必要范围设置 oAuth,然后调用我的 API 请求以从应用程序脚本获取数据。

const connectToDrive = async () => {

    const authToken = await window.gapi.auth2
      .getAuthInstance()
      .currentUser.get()
      .getAuthResponse().id_token;

    console.log('token', authToken);

    window.gapi.client.script.scripts
      .run({
        scriptId,
        resource: {
          function: 'setUpOrReadRoot',
        },
      })
      .then(resp => console.log('result', resp.result))
      .catch(err => console.log('err', err));
  };

我得到的错误是 401 UNAUTHENTICATED。

{
  "result": {
    "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"
    }
  },
  "body": "{\n  \"error\": {\n    \"code\": 401,\n    \"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.\",\n    \"status\": \"UNAUTHENTICATED\"\n  }\n}\n",
  "headers": {
    "date": "Thu, 04 Apr 2019 06:50:59 GMT",
    "content-encoding": "gzip",
    "server": "ESF",
    "content-type": "application/json; charset=UTF-8",
    "vary": "Origin, X-Origin, Referer",
    "cache-control": "private",
    "content-length": "228"
  },
  "status": 401,
  "statusText": null
}

在调用 api 之前,我正在注销我的访问令牌,所以我知道我已登录并拥有一个访问令牌。

如何将访问令牌显式附加到window.gapi.client.script.scripts.run()请求?

标签: javascriptgoogle-apps-scriptaccess-tokenhttp-status-code-401google-apps-script-api

解决方案


推荐阅读