How can I securely call a Google Cloud Function via a Google Apps Script?
? I have a Google Cloud Function, which I can access at https://MY_REGION-MY_PROJECT.cloudfunctions.net/MY_FUNCTION
, and which I would like to allow certain users to invoke via an Apps Script.
? To secure the Cloud Function, I have set Cloud Function Invoker to only include known email (e.g. [email protected]
, where this is a valid Google email).
? I am able to successfully invoke the Cloud Function via curl, while logged into gcloud with this email, by running: curl https://MY_REGION-MY_PROJECT.cloudfunctions.net/MY_FUNCTION -H "Authorization: Bearer $(gcloud auth print-identity-token)"
.
? I have granted the following oauthScopes in my Apps Script's manifest:
"https://www.googleapis.com/auth/script.external_request"
"https://www.googleapis.com/auth/userinfo.email"
"https://www.googleapis.com/auth/cloud-platform"
?? However, when I attempt to invoke the Cloud Function via a Google Apps Script, while logged in with the email [email protected]
, I am unable to invoke it and instead returned a 401. Here is how I have attempted to invoke the Cloud Function:
const token = ScriptApp.getIdentityToken();
const options = {
headers: {'Authorization': 'Bearer ' + token}
}
UrlFetchApp.fetch("https://MY_REGION-MY_PROJECT.cloudfunctions.net/MY_FUNCTION", options);
?? I have also tried the following:
- Using
ScriptApp.getOAuthToken()
- Adding additional oauthScopes, e.g.
openid
.
- Creating an OAuth Client ID with
https://script.google.com
set as an Authorized Javascript origin.
- Deploying the Apps Script.
- Crying out to the sky in utter, abject despair
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…