Google表格使用API​​密钥而不是client_secret.json

Mr.*_*vin 4 java google-api google-spreadsheet-api google-api-java-client google-oauth

Java QuickstartQuickStart.java上的示例中,它们用于标识应用程序,这会弹出一个窗口,要求提供Google凭据以使用该应用程序。您必须下载才能修改Google表格。OAuth client IDclient_secret.json

我的问题是:您可以使用API Key或其他方法来躲避弹出窗口询问Google凭据吗?并且,如果可能的话,如何更改Java代码以实现此目的?

DaI*_*mTo 5

您看到的弹出窗口是 Oauth2 同意屏幕。为了访问私人用户数据,您需要获得用户的同意才能访问他们的数据。

还有另一个选项称为服务帐户。如果您尝试访问的工作表是您作为开发人员可以控制的工作表,那么您可以使用服务帐户电子邮件地址创建服务帐户凭据并授予服务帐户访问该工作表的权限。

据我所知,使用 java 访问服务帐户的最佳示例是 Google Analytics(分析),您必须将其更改为 Google Sheets(Google 表格),如果您有任何问题,我可能可以提供帮助。 你好分析服务帐户。

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.io.IOException;


/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class HelloAnalytics {


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "<REPLACE_WITH_JSON_FILE>";
  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();

      String profile = getFirstProfileId(analytics);
      System.out.println("First Profile Id: "+ profile);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Initializes an Analytics service object.
   *
   * @return An authorized Analytics service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {

    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(AnalyticsScopes.all());

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }


  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No Webproperties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

仅当访问创建密钥的项目所拥有的资源时,API密钥才能工作。

对于电子表格之类的资源,通常需要访问用户拥有的资源。如果这将是很可怕,你有获得我的私人床单只是由具有API密钥。

因此,不,我不希望有任何方法可以避免获得使用用户文档的授权。但是,您应该能够使用Java OAuth库保留auth令牌,这样就可以避免多次询问。(当然,除非用户撤消访问权限。)

正如DalmTo所说,如果您要访问项目拥有的资源(或可以授予项目访问权限的资源),则可以使用服务帐户凭据。请注意,如果您在AppEngine,Google Kubernetes Engine或Google Compute Engine上运行,则该环境的服务帐户凭据应自动可用。