【问题标题】:How to authenticate Google Sheets using Service Account within Google Apps Script如何在 Google Apps 脚本中使用服务帐户对 Google 表格进行身份验证
【发布时间】:2019-04-22 10:22:40
【问题描述】:

我正在尝试创建一个 Google 应用程序,它将在 Google 表格中搜索关键字、请求(A 列)并返回响应(B 列)。该脚本运行良好,但每当最终用户调用该应用程序时,它都会请求访问表格的权限。

我想知道最终用户如何在未经许可的情况下访问该应用程序以及如何提供该应用程序以使用服务帐户来读取代码中的电子表格?

function ReadExcelFile() 
{
  var spreadsheetId = <MySpreadSheetID>;
  var sheet = SpreadsheetApp.openById(spreadsheetId); 

  var SearchText='Hello'; 
  var data = sheet.getRange('A:B').getValues(); 
  for(var i in data){
  if(i>0){
    var row = data[i][0];
    Logger.log('Searching for a KeyWord: '+SearchText+' From the SpreetSheet Value : '+row);
    var SearchCount=SearchText.indexOf(row);
    if(SearchCount>-1){    
    var row2=data[i][1];
    Logger.log(SearchCount+' '+row2);
    break;
    }    
   }    
  }  
 }
请求 |回复
你好 |你好欢迎!!
嘿|嘿欢迎!

输出将是.. Hi Welcome!!

【问题讨论】:

  • 虽然我不确定这是否是你想要的方向,但当你想使用服务帐户时,作为几种方法之一,使用这个库怎么样? github.com/gsuitedevs/apps-script-oauth2
  • 嗨 Tanike,感谢您的评论,我试过了,但我不确定如何在我的 App 脚本中配置此 Oauth2.. 任何帮助都非常感谢
  • 感谢您的回复。我很抱歉我的评论对你的情况没有用。关于I am not sure on how to configure this Oauth2 in my App script,我无法理解你的情况。您能否提供有关详细信息(您尝试了什么。以及您尝试的结果,如果出现错误,请显示。)?如果可以,请将其添加到您的问题中。提供详细信息将帮助用户思考您的解决方案。如果您能合作解决您的问题,我很高兴。

标签: google-apps-script google-sheets google-oauth google-sheets-api


【解决方案1】:

我也遇到过这个问题,我想读取容器绑定的电子表格数据,并在最终用户向谷歌聊天机器人发送消息时将其作为消息回复给最终用户,最后我通过这种方式解决了,它可能会有所帮助。 这是我的 appscript.json 代码

{
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "dependencies": {
    "libraries": [
      {
        "userSymbol": "OAuth2",
        "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF",
        "version": "26"
      }
    ],
    "enabledAdvancedServices": [
      {
        "userSymbol": "Sheets",
        "version": "v4",
        "serviceId": "sheets"
      }
    ]
  },
  "chat": {
    "addToSpaceFallbackMessage": "Thank you for adding me"
  }
}

这里是oauth、令牌访问和查询api代码

var PRIVATE_KEY = 'your service account private key generated Google Cloud Project (GCP) console ';
var CLIENT_EMAIL = 'clien-email';
var ssId = 'Spreadsheet Id which you want to read or write data from end user';


/**
 * Configures the Chatbot service.
 */
function getChatbotService() {
 return OAuth2.createService("sathibhai-bot")
 // Set the endpoint URL.
 .setTokenUrl("https://accounts.google.com/o/oauth2/token")
// Set the private key and issuer.
 .setPrivateKey(PRIVATE_KEY)
 .setIssuer(CLIENT_EMAIL)
// Set the property store where authorized tokens should be persisted.
 .setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope.
 .setScope("https://www.googleapis.com/auth/chat.bot");
}

/**
 * Configures the spreadsheet service.
 */
function getSpreasheetService() {
 return OAuth2.createService("spreadsheet")
 // Set the endpoint URL.
 .setTokenUrl("https://accounts.google.com/o/oauth2/token")
// Set the private key and issuer.
 .setPrivateKey(PRIVATE_KEY)
 .setIssuer(CLIENT_EMAIL)
// Set the property store where authorized tokens should be persisted.
 .setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope.
 .setScope("https://www.googleapis.com/auth/spreadsheets");
}

function readSheet(){
  var service = getSpreasheetService();
  var range = 'Sheet1!A1:D';
  var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + ssId +'/values/' + range;
  var response = UrlFetchApp.fetch(url, { headers: {Authorization: 'Bearer ' + service.getAccessToken() } }); 
  var rep = JSON.parse(response.getContentText());
  var values =  rep.values;
  for(row in values)
    Logger.log(values[row][0] + ":" + values[row][1] + ":" + values[row][2] + ":" + values[row][3]); //you can use these data as your requirements
}

注意:

  1. 与服务帐户 i.i your-service-account@sys-.................iam.gserviceaccount.com 共享您的电子表格(并且无需共享给除服务帐户之外的任何机构)
  2. 在 GCP 控制台中启用电子表格 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2019-05-01
    • 2013-09-23
    • 2019-08-25
    相关资源
    最近更新 更多