簡體   English   中英

如果私鑰未直接存儲在應用程序腳本文件中,則服務帳戶的Google Apps腳本OAuth2庫錯誤

[英]Google Apps Script OAuth2 Library Error for Service Accounts if private Key is not stored in apps script file directly

我已成功使用服務帳戶建立了從Google Apps腳本到Google Cloud firestore數據庫的連接。 只要我將憑據存儲在應用程序腳本文件本身中,它就可以正常工作。 如果我將憑據的私鑰存儲在其他地方(在數據庫中,在驅動器文件中,則是google doc ...),則oauth2身份驗證將失敗,並顯示以下錯誤:GAS Oauth2庫拋出了“無效參數:密鑰”。

我進行了進一步調查,似乎是編碼/字符集問題。 如果我比較硬編碼和存儲在文件/數據庫中的私鑰字符串的長度,則密鑰的長度不相等,但是密鑰字符串似乎是相同的。

一些幫助,將不勝感激。

function createOAuth() {

// credentials of service account hard coded 
var jsonObj = {
      "type": "service_account",
      "project_id": "id of project",
 "private_key": "-----BEGIN PRIVATE KEY-----.....----END PRIVATE KEY-\n",
      "client_email": "servic accoutn email",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",    
    }  

// not working if store attribute private_key somewhere else like:
/*var fileContent = DriveApp.getFileById('idOfFile').getBlob().getDataAsString("UTF-8"); //OR
DocumentApp.getBody().getText() //OR
var privateKey = Utilities.newBlob(privatKeyFromCredents).getDataAsString()
//store key in cloud firestore database also not working. 
*/

return OAuth2.createService("Service Account")
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')
  .setPrivateKey(jsonObj.private_key)
  .setIssuer(jsonObj.client_email)
   .setPropertyStore(PropertiesService.getScriptProperties())
  .setCache(CacheService.getScriptCache())
  .setParam('access_type', 'offline')
  .setScope('https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore');

var access = service.hasAccess(); // true if jsonObj is hard coded 
// false if stored somewhere else --> error: Invalid Argument: Key
Logger.log('Access: ' + access); 

}
// get Credentials form Drive in JSON format
var fileContent = DriveApp.getFileById('18t9NnzwKMlmQAnRUa_KovWdDvhk60oZT').getBlob().getDataAsString("UTF-8");

var serviceCredentials = JSON.parse(fileContent);
serviceCredentials['service_name'] = "Service Account Name";
serviceCredentials['scope'] = "https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/datastore ";

var service = OAuth2.createService(serviceCredentials.service_name)
.setTokenUrl(serviceCredentials.token_uri)
.setPrivateKey(serviceCredentials.private_key)
.setIssuer(serviceCredentials.client_email)
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setParam('access_type', 'offline')
.setScope(serviceCredentials.scope);

// for testing if access oauth setup is working or not
var access = service.hasAccess();
Logger.log('Access: ' + access); //true or false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM