Calling a Google Apps Script web app with access t

2019-04-13 09:41发布

I need to execute a GAS service on behalf of a user that is logged to my system. So I have her/his access token. I would like somehow to transfer the token to the web app and without having to authorize again the user to use it for some activities. Can this be accomplished? Thank you.

EDIT: I think I didn't explain right what I try to accomplish. Here is the work flow I try to achieve:

  1. We authorize a user visiting our website using OAuth2 and Google;
  2. We get hold of her/his access token that Google returns;
  3. There is a Google Apps Script web app that is executed as the user running the web app;
  4. We want to call this app (3) by providing the access token (2) so Google not to ask again for authorization;
  5. Actually, we want to call this app (3) not by redirecting the user to it but by calling it as a web service.

Thanks

2条回答
淡お忘
2楼-- · 2019-04-13 10:06

The hard answer is NO you can't use the built-in services of Apps Script with a service token. But if you already have the token for a user generated by a service account, access to the users data is pretty similar to any other language. All calls would be to the REST interface of the service your token is scoped for.

Take this small script for example. It will build a list of all the user's folders and return them as JSON:

 function doGet(e){
  var token = e.parameter.token;
  var folderArray = [];
  var pageToken = "";
  var query = encodeURIComponent("mimeType = 'application/vnd.google-apps.folder'");
  var params = {method:"GET",
                contentType:'application/json',
                headers:{Authorization:"Bearer "+token},
                muteHttpExceptions:true
               };

  var url = "https://www.googleapis.com/drive/v2/files?q="+query;

  do{
    var results = UrlFetchApp.fetch(url,params); 
    if(results.getResponseCode() != 200){
      Logger.log(results);
      break;
    }

    var folders = JSON.parse(results.getContentText());
    url = "https://www.googleapis.com/drive/v2/files?q="+query;  

    for(var i in folders.items){
      folderArray.push({"name":folders.items[i].title, "id":folders.items[i].id})
    }

    pageToken = folders.nextPageToken;
    url += "&pageToken="+encodeURIComponent(pageToken);
  }while(pageToken != undefined)

  var folderObj = {};
  folderObj["folders"] = folderArray;      
  return ContentService.createTextOutput(JSON.stringify(folderObj)).setMimeType(ContentService.MimeType.JSON);
}

You do miss out on a lot of the convenience that makes Apps Script so powerful, mainly the built in services, but all functionality is available through the Google REST APIs.

查看更多
相关推荐>>
3楼-- · 2019-04-13 10:16

I found a way! Just include the following header in the request:

Authorization: Bearer <user's_access_token>

查看更多
登录 后发表回答