首页 > 解决方案 > 使用服务帐户从 Java 应用程序访问 BigQuery 的 GCloud Auth 无法正常工作

问题描述

我想访问 BigQuery 以从我的 JAVA 应用程序的表中选择数据。首先,我创建了一个服务帐户并授予 BigQuery 管理员权限。服务帐户的 Json 作为环境变量传递,我使用如下代码(从https://cloud.google.com/docs/authentication/production获取)

static void authImplicit() {
  // If you don't specify credentials when constructing the client, the client library will
  // look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.
  Storage storage = StorageOptions.getDefaultInstance().getService();

  System.out.println("Buckets:");
  Page<Bucket> buckets = storage.list();
  for (Bucket bucket : buckets.iterateAll()) {
    System.out.println(bucket.toString());
  }
}

该方法返回 401 并带有以下错误响应:

引起:com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized { "code" : 401, "errors" : [ { "domain" : "global", "location" : "Authorization", "locationType " : "header", "message" : "需要登录。", "reason" : "required" } ], "message" : "请求缺少必需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效身份验证凭证。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。”,“状态”:“未验证”}

标签: google-cloud-platformgoogle-bigquerygoogle-oauth

解决方案


从您的描述看来,您没有将 json 文件放在环境变量中描述的路径中。这是假设您在属性文件中正确描述了您的项目 ID,您已在 Google Cloud Platform 中启用了所需的 API。为了更精确地确定这一点,我需要您与我们分享您的文件夹结构和属性文件。

我建议你使用 CredentialsProvider 接口来解决这个问题

public interface CredentialsProvider {
  Credentials getCredentials() throws IOException;
}

您可以在此处找到有关此界面的更多信息。

您还可以查看Spring 团队为 spring + bigquery 制作的快速入门


推荐阅读