简体   繁体   English

从 Google AppScript 调用经过身份验证的云 function

[英]Invoking an Authenticated cloud function from Google AppScript

I have seen many questions in invoking cloud functions from AppScript, but I am unable to invoke the function from any of those methods.我在从 AppScript 调用云函数时看到很多问题,但我无法从任何这些方法调用 function。 Here are the things I have already checked:以下是我已经检查过的内容:

[x] - Invoke successful from Google Cloud Testing Tab [x] - 从谷歌云测试选项卡调用成功

[x] - Invoke successful from command line: curl <CLOUD_FUNCTION_URI> -H "Authorization: bearer $(gcloud auth print-identity-token)" [x] - 从命令行调用成功: curl <CLOUD_FUNCTION_URI> -H "Authorization: bearer $(gcloud auth print-identity-token)"

[x] - Invoke successful from Call API: gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Keyboard Cat"}' [x] - 从呼叫 API 调用成功: gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Keyboard Cat"}'

[x] - Invoke successful from Python client library: [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)

where my invoker Class looks like this:我的调用者 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)

But when I try to invoke the same function using app script as shown below:但是当我尝试使用应用程序脚本调用相同的 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());

  }
}

I get a 401 unauthorized error.我收到 401 未经授权的错误。

I have tried using both identity token and OAuth token, but none of them works.我试过同时使用身份令牌和 OAuth 令牌,但它们都不起作用。

Additionally, I have also set up my manifest.json to include scopes:此外,我还设置了 manifest.json 以包含范围:

"oauthScopes": [
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/script.external_request"
  ],

Finally, I changed my project to work within the google cloud project environment:最后,我将我的项目更改为在 google 云项目环境中工作: 在此处输入图像描述

But none of these worked for me.但这些都不适合我。 Here's the command I used to deploy my cloud function:这是我用来部署我的云 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`

I wrote an article on that topic, but focus on Cloud Run.我写了一篇关于该主题的文章,但重点是 Cloud Run。

The security principle on Cloud Run and Cloud Functions is the same (the same underlying infrastructure is shared between both). Cloud Run 和 Cloud Functions 的安全原则是相同的(两者共享相同的底层基础设施)。 So you should be able to achieve what you want with that article.所以你应该能够通过那篇文章实现你想要的。 If not, let me know I will help you.如果没有,请告诉我我会帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 向 Google Cloud 发出经过身份验证的请求 Function - Making authenticated request to Google Cloud Function 如何通过 Next.js(带有 Typescript)应用程序调用经过身份验证的 HTTP 触发器 Google Cloud Function? - How Do I Call An Authenticated HTTP Trigger Google Cloud Function Via A Next.js (with Typescript) App? 错误:7 PERMISSION_DENIED:您的应用程序已使用来自 Google Cloud SDK 的最终用户凭据进行了身份验证 - Error: 7 PERMISSION_DENIED: Your application has authenticated using end user credentials from the Google Cloud SDK 如何以我使用 gcloud CLI 进行身份验证的方式从 Java 对 google cloud API 进行身份验证 - How to auth google cloud API from Java in the same way I authenticated with gcloud CLI 将数据从 Google Cloud 保存到 Firestore Function - Saving data to Firestore from Google Cloud Function PERMISSION_DENIED:您的应用程序已使用来自 Google Dialogflow 中的 Google Cloud SDK 的最终用户凭据进行了身份验证 - PERMISSION_DENIED: Your application has authenticated using end user credentials from the Google Cloud SDK in Google Dialogflow 从谷歌云返回的错误请求 function - Bad request returned from google cloud function 从 Blazor WASM 调用 Google Cloud Function - Calling Google Cloud Function from Blazor WASM 使用 Python 和 SQLAlchemy 从谷歌云 Function 连接到云 SQL - Connecting to Cloud SQL from Google Cloud Function using Python and SQLAlchemy Python3 中的 Cloud Function - 从 Google Cloud Bucket 复制到另一个 Google Cloud Bucket - Cloud Function in Python3 - copy from Google Cloud Bucket to another Google Cloud Bucket
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM