1
votes

My application uses multiple API's all succesful under the same auth init - except for Apps Script execution API which throws error code 401 with the following 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."

I am using the same Google Cloud Project id, the Apps Script function API executable is correctly set. Sending email API and getting a file from Drive API are working perfectly. Except this one. I am running them on localhost.

I will trim down the code to only zoom into the most relevant parts that I believe could be the problem.

<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>

And this is the function that fails:

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

1 Answers

0
votes

I found the solution: Code 401 was returning because I didn't have the correct scopes, I went into my Google Apps Script > File > Properties > Scopes to see what were the scopes I was really needing, turns out I was missing one scope.

I added this and everything ran perfectly.