使用服务帐号权限调用google Cloud功能

问题描述 投票:0回答:1

我想调用带认证的云函数。服务帐户 my-project-crendential 具有 Cloud Functions-Invoker 角色。 于是实现了java代码来调用名为my-test-function的云函数

ServiceAccountCredentials
            .fromStream(new FileInputStream(PATH != null ? PATH : "my-project-crendential.json"))

this.settings = CloudFunctionsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(this.credentials))
            .build();


try (CloudFunctionsServiceClient client = CloudFunctionsServiceClient.create(this.settings)) {
      final var functionNameWithLocation = String.format(
          "projects/%s/locations/%s/functions/%s",
          "my-project-id",
          "europe-west4",
          "my-test-function"
      );
      CallFunctionRequest request = CallFunctionRequest.newBuilder()
             .setName(functionNameWithLocation)
             .setData(body.encode())
             .build();
      CallFunctionResponse response = client.callFunction(request);

      log.atDebug().log("Function response received {} ...", response.getResult());
            
 } catch (Exception e) {
      log.atError().withThrowable(e).log("Create repository failed ...");
 }

该函数存在,网址为https://europe-west4-my-project-id.cloudfunctions.net/my-test-function

但是我总是收到异常:

io.grpc.StatusRuntimeException:PERMISSION_DENIED:“locations/europe-west4”的权限被拒绝(或者可能不存在)

所以我不认为权限是错误的,因为异常写入的位置不存在,但这不是真的。 我使用依赖项:

<dependency>
     <groupId>com.google.cloud</groupId>
     <artifactId>google-cloud-functions</artifactId>
     <version>2.35.0</version>
</dependency>

如何使用服务帐号权限调用云函数?

java authentication google-cloud-platform google-cloud-functions
1个回答
0
投票

您悲伤地感到陷入了陷阱...您是对的,Cloud Functions 库中有一个 CALL API。但是,您必须知道库只是调用 Google Cloud 上的 API 的包装器。

CALL API 就是这个one。如您所见,它仅用于测试,不适用于常规调用。


如果您想使用 Cloud Functions 库,您必须执行 2 件事:

  • 使用 GET API(与 Java 库一起使用此请求)获取详细信息并提取 HTTPStrigger.URL 属性
  • 使用 OAuth2 库生成身份令牌,将其添加到请求的授权标头(承载令牌)中,并对提取的 URL 执行 HTTP 调用

这才是云函数的正确使用方法。

© www.soinside.com 2019 - 2024. All rights reserved.