使用带有 Java API 的服务帐户对 Google API 进行身份验证 [英] Authenticating Google API with a service account with Java API

查看:31
本文介绍了使用带有 Java API 的服务帐户对 Google API 进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 oauth API 通过 Java API 对 Google 服务帐户进行身份验证.我希望用它来访问 Google Bigquery.我的 API 请求返回了无效授权".

I am attempting to use oauth API to authenticate a google service account through the Java API. I am hoping to use it to access Google Bigquery. I get an "invalid grant" returned from my API requests.

这是代码,它是一个基本身份验证示例的副本(不是用于 Bigquery ..而是另一个 Google API):

Here is the code, which is a copy of a basic authentication example (which wasn't for Bigquery.. but another Google API):

  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  private static Bigquery bigquery;  

public ServiceAccountExample() {

      try {
          try {

            GoogleCredential credential = new  GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(BigqueryScopes.BIGQUERY)
                .setServiceAccountPrivateKeyFromP12File(new File("GoogleBigQuery-privatekey.p12"))
                //.setRefreshListeners(refreshListeners)
                //.setServiceAccountUser("email.com")
                .build();


            credential.refreshToken();

            bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                        //.setApplicationName("GoogleBigQuery/1.0")
                        .build();

            listDatasets(bigquery, "publicdata");

            return;
          } catch (IOException e) {
            System.err.println(e.getMessage());
          }
        } catch (Throwable t) {
          t.printStackTrace();
        }

}

SERVICE_ACCOUNT_EMAIL 是表单的电子邮件地址:XXXXXXX@developer.gserviceaccount.com

SERVICE_ACCOUNT_EMAIL is the email address of the form: XXXXXXX@developer.gserviceaccount.com

如果我删除 credential.refreshToken() 行,它会在第一次调用 Bigquery 时在listsDatasets 中失败...否则它会在 credential.refreshToken() 上失败...并出现相同的错误.

If I remove the credential.refreshToken() line, it fails in the listsDatasets on the first call to Bigquery... Otherwise it fails on credential.refreshToken().. with the same error.

BigQuery 不接受服务帐号身份验证吗?

Does BigQuery not accept Service Account authentication?

我相信我已经通过 API 控制台正确地完成了所有事情.我有:

I believe I have done everything correctly through the API Console. I have:

  • 开启了对 Big Query API 的访问.
  • 在API 访问"选项卡下创建了一个服务帐户.
  • 下载了我的私钥(从上面的代码中引用).
  • 为我的服务帐户用户提供团队"标签下的可以编辑"访问权限.
  • 启用计费.

我错过了什么吗?我还有什么需要做的吗?

Have I missed anything? Is there anything else I need to do?

谢谢..

推荐答案

服务帐号授权方法与 BigQuery 配合得很好.您不需要调用 credential.refreshToken().确保您的私钥文件可以从您的应用程序中读取.下面是一个例子:

The service account authorization method works just fine with BigQuery. You don't need to call credential.refreshToken(). Make sure that your private key file can be read from your application. Here is an example:

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;

import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryScopes;
import com.google.api.services.bigquery.Bigquery.Projects;
import com.google.api.services.bigquery.model.*;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;

public class BigQueryJavaServiceAccount {

  public static void main(String[] args) throws IOException, InterruptedException, GeneralSecurityException {

    final HttpTransport TRANSPORT = new NetHttpTransport();
    final JsonFactory JSON_FACTORY = new JacksonFactory();

    GoogleCredential credential = new  GoogleCredential.Builder()
      .setTransport(TRANSPORT)
      .setJsonFactory(JSON_FACTORY)
      .setServiceAccountId("SOMETHING@developer.gserviceaccount.com")
      .setServiceAccountScopes(BigqueryScopes.BIGQUERY)
      .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
      .build();

    Bigquery bigquery = Bigquery.builder(TRANSPORT, JSON_FACTORY)
      .setHttpRequestInitializer(credential)
      .build();

    Projects.List projectListRequest = bigquery.projects().list();
    ProjectList projectList = projectListRequest.execute();
    List<ProjectList.Projects> projects = projectList.getProjects();
    System.out.println("Available projects
----------------
");
    for (ProjectList.Projects project : projects) {
      System.out.format("%s
", project.getProjectReference().getProjectId());
    }
  }
}

这篇关于使用带有 Java API 的服务帐户对 Google API 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆