[英]Invoking an Authenticated cloud function from Google AppScript
我在從 AppScript 調用雲函數時看到很多問題,但我無法從任何這些方法調用 function。 以下是我已經檢查過的內容:
[x] - 從谷歌雲測試選項卡調用成功
[x] - 從命令行調用成功: curl <CLOUD_FUNCTION_URI> -H "Authorization: bearer $(gcloud auth print-identity-token)"
[x] - 從呼叫 API 調用成功: gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Keyboard Cat"}'
[x] - 從 Python 客戶端庫調用成功:
from modules.cloudInvoker import CloudFunctionInvoker
from os import environ
uri = environ['URI']
invoker = CloudFunctionInvoker(service_account_path=r'secrets/service.json',
endpoint=uri)
if __name__ == '__main__':
response = invoker.session.post(uri,json={
"test":True
})
print(response)
我的調用者 Class 看起來像這樣:
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
class CloudFunctionInvoker:
def __init__(self,service_account_path:str,endpoint:str)->None:
try:
self.path = service_account_path
self.creds = service_account.IDTokenCredentials.from_service_account_file(service_account_path, target_audience=endpoint)
self.session = AuthorizedSession(self.creds)
except Exception as e:
raise(e)
def updateEndpoint(self,new_endpoint:str)->None:
try:
self.creds = service_account.IDTokenCredentials.from_service_account_file(self.path, target_audience=new_endpoint)
self.session = AuthorizedSession(self.creds)
except Exception as e:
raise(e)
但是當我嘗試使用應用程序腳本調用相同的 function 時,如下所示:
const cloudFunctionInvoker = (payload,cloud_function_uri) => {
const token = ScriptApp.getIdentityToken();
// const token = ScriptApp.getOAuthToken();
const headers = { "Authorization": "Bearer " + token };
const options = {
"method": "post",
"headers": headers,
"muteHttpExceptions": true,
"contentType": "application/json",
"payload": JSON.stringify(payload||{})
};
const response = UrlFetchApp.fetch(cloud_function_uri, options);
try{
const response_object = JSON.parse(response.getContentText());
console.log(response_object);
}
catch(e) {
console.log("Error = ", e.message);
console.log(response.getContentText());
}
}
我收到 401 未經授權的錯誤。
我試過同時使用身份令牌和 OAuth 令牌,但它們都不起作用。
此外,我還設置了 manifest.json 以包含范圍:
"oauthScopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/script.external_request"
],
最后,我將我的項目更改為在 google 雲項目環境中工作:
但這些都不適合我。 這是我用來部署我的雲 function 的命令:
gcloud functions deploy <function_name> --entry-point main --runtime python39 --source . --timeout 540 --trigger-http
Allow unauthenticated invocations of new function <function_name>?
(y/N)? n
WARNING: Function created with limited-access IAM policy. To enable unauthorized access consider `gcloud alpha functions add-iam-policy-binding <function_name> --region=us-central1 --member=allUsers --role=roles/cloudfunctions.invoker`
我寫了一篇關於該主題的文章,但重點是 Cloud Run。
Cloud Run 和 Cloud Functions 的安全原則是相同的(兩者共享相同的底層基礎設施)。 所以你應該能夠通過那篇文章實現你想要的。 如果沒有,請告訴我我會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.