使用Java API的服务帐户验证Google API [英] Authenticating Google API with a service account with Java API

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

问题描述

我试图使用oauth API通过Java API对Google服务帐户进行身份验证。我希望用它来访问Google BigQuery。我收到了API请求返回的无效授权。



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

  / ** HTTP传输的全局实例。 * / 
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/ ** JSON工厂的全局实例。 * /
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

private static Bigquery bigquery;

public ServiceAccountExample(){

try {
try {

GoogleCredential凭证=新的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,凭证)
//.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是电子邮件地址form:XXXXXXX@developer.gserviceaccount.com



如果我删除了credential.refreshToken()行,它会在第一次调用Bigquery时在列表数据集中失败......否则它会失败凭证.refreshToken()..与相同的错误。

是否BigQuery不接受服务帐户身份验证?



我相信我已通过API控制台正确地完成了一切。我有:


  • 打开了对Big Query API的访问。

  • 创建了一个服务帐户
  • 下载我的私钥(从上面的代码中引用)。
  • 假设我的服务帐户用户可以编辑权限。

  • 已启用结算。



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



谢谢..

解决方案

服务帐户授权方法适用于BigQuery。您无需调用 credential.refreshToken()。确保您的私钥文件可以从您的应用程序中读取。以下是一个示例:

  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凭证=新的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(凭证)
.build();

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


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.

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 is the email address of the form: XXXXXXX@developer.gserviceaccount.com

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.

Does BigQuery not accept Service Account authentication?

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

  • Turned access to the Big Query API on.
  • Created a service account under the "API Access" tab.
  • Downloaded my private key (which is referenced from the code above).
  • Given my service account user "can edit" access under the "Teams" tab.
  • Enabled Billing.

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

Thanks..

解决方案

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\n----------------\n");
    for (ProjectList.Projects project : projects) {
      System.out.format("%s\n", project.getProjectReference().getProjectId());
    }
  }
}

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

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