在JAVA中生成GCP身份验证身份令牌

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

我正在寻找用 Java 生成 GCP 身份令牌的方法。我可以通过 gcloud cli 生成它,如下所示

./bin/gcloud auth print-identity-token
。但找不到用 Java 客户端做类似事情的方法。

请分享一些关于如何创建此内容的见解。 预先感谢。

java google-cloud-platform token gcloud
1个回答
0
投票

请考虑以下这些方法,就像文档中的那样。

以编程方式生成令牌

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
import java.io.IOException;

public class Authentication {

  // makeGetRequest makes a GET request to the specified Cloud Run or
  // Cloud Functions endpoint `serviceUrl` (must be a complete URL), by
  // authenticating with an ID token retrieved from Application Default
  // Credentials using the specified `audience`.
  //
  // For Cloud Functions, endpoint (`serviceUrl`) and `audience` are the same.
  // Example `audience` value (Cloud Functions): https://project-region-projectid.cloudfunctions.net/myFunction
  public static HttpResponse makeGetRequest(String serviceUrl, String audience) throws IOException {
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    if (!(credentials instanceof IdTokenProvider)) {
      throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider.");
    }
    IdTokenCredentials tokenCredential =
        IdTokenCredentials.newBuilder()
            .setIdTokenProvider((IdTokenProvider) credentials)
            .setTargetAudience(audience)
            .build();

    GenericUrl genericUrl = new GenericUrl(serviceUrl);
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential);
    HttpTransport transport = new NetHttpTransport();
    HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl);
    return request.execute();
  }
}

手动生成代币

如果您正在调用一个函数并且对于某些 无法使用身份验证库的原因有两种方法 您可以使用计算元数据手动获取 ID 令牌 服务器或通过创建自签名 JWT 并将其交换为 Google 签名的 ID 令牌。

还有

向您的请求提供身份验证凭据,作为存储在授权标头中的 Google 生成的 ID 令牌。例如,通过运行以下命令使用 gcloud 获取 ID 令牌:

curl  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \ https://FUNCTION_URL

其中 FUNCTION_URL 是函数的 URL。从 Google Cloud 控制台的 Cloud Functions 页面检索此 URL,或者通过运行 gcloud 函数描述命令(如 Google Cloud CLI 部署命令示例的第一步所示)来检索此 URL。

请告诉我。

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