将凭证从JSON密钥文件传递到Big Query

时间:2018-08-01 14:43:20

标签: google-cloud-platform google-bigquery google-cloud-iam

我正在使用公共文档中的this example从Java客户端连接到Big Query。

出现错误消息:

  

“该类型的方法setCredentials(Credentials)   ServiceOptions.Builder引用缺少的凭据类型

我想念什么?

import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryResponse;
import com.google.cloud.bigquery.TableResult;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

public void connectBQ() {

  GoogleCredentials credentials1;
  File credentialsPath = new File("service_account.json");  // TODO: update to your key path.
  try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
    credentials1 = ServiceAccountCredentials.fromStream(serviceAccountStream);
  }

  // Instantiate a client.
  BigQuery bigquery = BigQueryOptions.newBuilder().setCredentials(credentials1).build().getService();
  BigQuery bigquery1= BigQueryOptions.newBuilder().setCredentials(credentials1).setProjectId("1234").build().getService();

  // Use the client.
  System.out.println("Datasets:");
  for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
    System.out.printf("%s%n", dataset.getDatasetId().getDataset());
  }

1 个答案:

答案 0 :(得分:0)

当客户端对象尝试使用无效的GCP凭据向您的GCP帐户服务进行身份验证时,通常会引发此类问题。基于此,您用来初始化凭据路径变量的服务帐户文件路径可能无效,从而导致尝试连接到服务时setCredentials方法失败。

  

文件凭据路径=新文件(“ service_account.json”); // TODO:更新到您的关键路径。

我建议您验证自己使用的是JSON凭证密钥文件的正确文件路径,并查看Getting Started with Authentication指南,该指南说明了创建Service account,{如果您尚未创建{3}}和Service account key (JSON file)角色。这样,您将可以使用它们来初始化您的certificatePath变量并实现Google的示例,而不会出现问题。