Apps script throws 'invalid state token' a

2019-07-31 10:14发布

问题:

I wish to authorize my webapp to create a folder in the user's appfolder to hold the app's data files.

To do this, I need to request the scope https://www.googleapis.com/auth/drive.appfolder

So far I have the following code:

var CLIENT_ID            = '3941...';
var CLIENT_SECRET        = 'DY_P...';
var SCRIPT_ID            = '1XAF...';

var appfolder_scope     = 'https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.appfolder';
var redirectURI         = 'https%3A%2F%2Fscript.google.com%2Fmacros%2Fd%2F'+ SCRIPT_ID + '%2Fusercallback';
var AuthEndpoint        = 'https://accounts.google.com/o/oauth2/v2/auth';



function getCallbackURL(callbackFunction) {

   var url = ScriptApp.getService().getUrl();      // Ends in /exec (for a web app)
   url = url.slice(0, -4) + 'usercallback?state='; // Change /exec to /usercallback
   var stateToken = ScriptApp.newStateToken()
        .withMethod(callbackFunction)
        .withTimeout(120)
        .createToken();
   return url + stateToken;
}


function generateAuthRequestURL() {
  var AuthRequest = AuthEndpoint;
  var Query = '?'
      + 'scope=profile%20' + appfolder_scope
      + '&state=' + getCallbackURL(cb)
      + '&redirect_uri=' + redirectURI
      + '&response_type=code'
      + '&client_id=' + CLIENT_ID
    //+ '&login_hint=...%40gmail.com'
      ;
  AuthRequest += Query;
  Logger.log(AuthRequest);      
  return AuthRequest;
}

function cb(response) {
  Logger.log(response);
}

When I click on the url generated by the generateAuthRequestURL() it takes me to the consent screen where I click allow. But then every time I get 'The state token is invalid or has expired'.

The webapp is published and I have tested both the exec and dev versions with the same result. I have also tried with and without a login_hint.

I have also experimented with Apps-Script-Folder-Library as well as gdrive-appdata. I couldn't get the first one to work, and the second one I don't even know how to use.

回答1:

Based from this thread, make sure that you've put the project key into the related field. This error may occur when the key changed after making a copy of the script.

You can also check on this issue which suggested to ensure that you are using the right project key.

Here are some related forums which might also help:

  • Issues with OAuth 2.0 Library for Google Apps Scripts
  • OAuth2 support through library returns The state token is invalid or has expired. Please try again