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