首页 > 解决方案 > 使用适用于 Java 的 Google API 库对 Google 云进行身份验证

问题描述

我正在尝试使用 Java 的 API 客户端库创建一些 GCP VM,但是我看到的示例似乎很旧。我从这个https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/compute/cmdline/src/main/java/ComputeEngineSample.java开始,但看起来GoogleCredential该类已被弃用。经过一番研究,我想出了这段代码

        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        if (credentials.createScopedRequired()) {
            List<String> scopes = new ArrayList<>();
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            scopes.add(ComputeScopes.DEVSTORAGE_READ_WRITE);
            credentials = credentials.createScoped(scopes);
        }
        Compute compute = new Compute.Builder(httpTransport, jsonFactory, null)
            .setApplicationName("et").build();
        Compute.Instances.List instancesList = compute.instances().list("<GCP-PROJECT>", "us-central1-a");
        InstanceList executedOperation = instancesList.execute();

接下来,我将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为我的服务帐户 json 文件的路径并运行我的代码,但它失败并出现401 Unauthorized错误。部分留言是这个

"message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.

我看到的示例适用于其他 Google 产品,例如 Storage、Pubsub 等,但我找不到任何有关如何使用我的凭据来调用Compute服务上的某些操作的相关示例。任何帮助,将不胜感激。

标签: javagoogle-cloud-sdk

解决方案


我拿了谷歌样本,它对我有用。

我将其缩写为仅枚举实例。

PROJECT=
ZONE=
INSTANCE=
ACCOUNT=

gcloud projects create ${PROJECT}

gcloud alpha billing projects link ${PROJECT} \
--billing-account=${BILLING}

gcloud services enable compute.googleapis.com \
--project=${PROJECT}

# Create an instance to enumerate
gcloud compute instances create instance-1 \
--project=${PROJECT}  \
--zone=${ZONE} \
--machine-type=f1-micro \
--image-family=debian-10 \
--image-project=debian-cloud \
--preemptible

gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}

gcloud iam service-accounts keys create ./${ACCOUNT}.json \
--iam-account=${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com \
--project=${PROJECT}

# Overly broad permissions but...
gcloud projects  add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com \
--role=roles/compute.admin

export GOOGLE_APPLICATION_CREDENTIALS=./${ACCOUNT}.json
mvn exec:java -Dexec.mainClass="com.dazwilkin.gce.App"

产量(为清楚起见进行了编辑):

[INFO] Scanning for projects...
[INFO] 
[INFO] -----------------------< com.dazwilkin.gce:gce >------------------------
[INFO] Building gce 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ gce ---
Hello Freddie!
================== Listing Compute Engine Instances ==================
{
  "id" : "6020825766320745087",
  "kind" : "compute#instance",
  "name" : "instance-1",
}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.088 s
[INFO] Finished at: 2020-05-13T17:54:51-07:00
[INFO] ------------------------------------------------------------------------

pom.xml

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dazwilkin.gce</groupId>
  <artifactId>gce</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>gce</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.9</source>
          <target>1.9</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.30.9</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-compute</artifactId>
      <version>v1-rev235-1.25.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

更新:google-auth-library

google-auth-library文档:


import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.http.HttpCredentialsAdapter;

import com.google.api.client.http.HttpRequestInitializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class App 
{

    public static void main(String[] args )
    {

    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    ...

    HttpRequestInitializer requestInitializer =
        new HttpCredentialsAdapter(credentials);
    Compute compute =
        new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
    ...

}

pom.xml

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dazwilkin.gce</groupId>
  <artifactId>gce</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>gce</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.9</source>
          <target>1.9</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.30.9</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-compute</artifactId>
      <version>v1-rev235-1.25.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-credentials</artifactId>
      <version>0.20.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>0.20.0</version>
    </dependency>
  </dependencies>
</project>

推荐阅读