我一直在尝试(很少成功)通过来自Google工作表的http请求(谷歌应用程序脚本)触发谷歌云功能,但这似乎行不通。一些重要的事情:
我知道这可以在Google colabs和Python中轻松完成。以下脚本将使我组织中Gem项目中 not 以外的用户触发云功能:
import requests
import google.auth
from google.auth.transport.requests import Request
from google.colab import auth
credentials, project_id = google.auth.default()
request = Request()
credentials.refresh(request=request)
GCF_URL = ''https://project_location-project_id.cloudfunctions.net/name-of-your-funciton''
resp = requests.get(GCF_URL, headers={'Authorization': f'Bearer {credentials.id_token}'})
这将对我组织内的任何用户起作用并触发云功能,但不适用于我的个人电子邮件。
现在,我想在Google Apps脚本中复制此行为,以便有权访问该工作表的最终用户只要是我组织的成员就可以触发云功能。
我尝试了一些我在网上看到的东西,例如:
function callExternalUrl() {
var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';
var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token
const data = {
oauthToken, // 1. add the oauth token to the payload
activeUser: param.user // 2. this here is important as it adds the userinfo.email scope to the token
// any other data you need to send to the Cloud Function can be added here
};
var options = {
'method' : 'get', // or post, depending on how you set up your Cloud Function
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
}
这会产生403错误,但如果我对其进行更改,以使其以正确的格式提供OAuth,如下所示:
function callExternalUrl() {
var url = 'https://project_location-project_id.cloudfunctions.net/name-of-your-funciton';
var oauthToken = ScriptApp.getOAuthToken(); // get the user who's logged into Google Sheet's OAuth token
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oauthToken
}
});
// const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
}
我收到401(即授权失败)。现在,看来我只需要从用户那里获得正确的身份验证即可发送此请求以使其正常工作。我已经看到了这个github存储库,该存储库侧重于从Google Apps脚本(https://github.com/gsuitedevs/apps-script-oauth2)中获取OAuth2,但是我似乎也无法使其正常工作,它必须以某种我不知道的方式适应云计算的。
我已阅读
Securely calling a Google Cloud Function via a Google Apps Script
这非常相似,但是似乎没有找到问题的根源,有关如何使此过程成为可能的任何投入?