Apps脚本执行API返回未经身份验证的

时间:2018-12-20 21:26:38

标签: javascript google-apps-script-api

我的应用程序在同一auth初始化下使用多个API都成功-除了Apps脚本执行API会抛出错误代码401并显示以下消息: “请求缺少必需的身份验证凭据。预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。”

我使用了相同的Google Cloud Project ID,并且正确设置了Apps脚本功能API可执行文件。发送电子邮件API并从云端硬盘API获取文件非常有效。除了这个。我正在本地主机上运行它们。

我将整理代码以仅放大我认为可能是问题的最相关部分。

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script>

<script>
window.onLoadCallback = function(){
gapi.load('auth2', initSigninV2);
};

function initSigninV2() {
    gapi.auth2.init({
            apiKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
            discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest","https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest","https://script.googleapis.com/$discovery/rest?version=v1"],
            clientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
            scope: 'https://www.googleapis.com/auth/drive'+' https://www.googleapis.com/auth/gmail.send'+' https://www.googleapis.com/auth/script.scriptapp'
    }).then(function (authInstance) {
        if(!gapi.auth2.getAuthInstance().isSignedIn.get()) {
        gapi.auth2.getAuthInstance().signIn();

        }
                 // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

    });
}

</script>

这是失败的功能:

function appScript(callback, data, field, dl) {
    var scriptId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    var request = {
        'function': 'doPost',
        'parameters': {'data':JSON.stringify(data)}
    };
    var headers = getClientRequestHeaders();
    console.log(headers);

    gapi.client.request({
        'root': 'https://script.googleapis.com',
        'path': 'v1/scripts/' + scriptId + ':run',
        'method': 'POST',
        'headers': headers,
        'body': request
    }).then(function (response) {
            console.log(response);
    //      callback(response.fileid, response.id, field);
    //      if (dl) {
    //      dl(response.fileid);
    //      }
        });
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:因为没有正确的作用域,所以返回了代码401,我进入Google Apps脚本>“文件”>“属性”>“作用域”,以查看我真正需要的作用域是什么,缺少一个范围。

我添加了此内容,一切运行正常。