【问题标题】:Invoking an Authenticated cloud function from Google AppScript从 Google AppScript 调用经过身份验证的云函数
【发布时间】:2021-11-18 21:48:17
【问题描述】:

我在从 AppScript 调用云函数时看到了很多问题,但我无法从这些方法中的任何一个调用该函数。以下是我已经检查过的内容:

[x] - 从 Google Cloud 测试选项卡调用成功

[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)

我的调用程序类如下所示:

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)

但是当我尝试使用如下所示的应用脚本调用相同的函数时:

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"
  ],

最后,我将我的项目更改为在谷歌云项目环境中工作:

但这些都不适合我。这是我用来部署云功能的命令:

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`

【问题讨论】:

    标签: google-apps-script google-cloud-functions


    【解决方案1】:

    我就该主题写了article,但重点关注 Cloud Run。

    Cloud Run 和 Cloud Functions 的安全原则相同(两者共享相同的底层基础架构)。所以你应该能够通过那篇文章实现你想要的。如果没有,请告诉我,我会帮助你。

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2022-06-13
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      相关资源
      最近更新 更多