[英]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.