在JAVA中不使用Web浏览器对Google Analytics进行身份验证

时间:2015-01-09 16:30:40

标签: java authentication google-analytics oauth-2.0

我目前有一个Google分析程序,可以从我的网站中提取一些分析数据。目前它位于我的本地机器上并且工作正常。但是,我想将程序移动到托管我的Web文件的Oracle云服务器中。它是一个基于Linux的服务器,几乎没有浏览器支持。我试过在服务器上运行该程序,但像往常一样,它提示我去一个网站来验证Oauth ..ect.ect

https://accounts.google.com/o/oauth2/auth?client_id=658818029220-701kg25os6dqq1ua577cpn8drujjuvl8.apps.googleusercontent.com&redirect_uri=http://localhost:23100/Callback&response_type=code&scope=https://www.googleapis.com/auth/analytics.readonly

我尝试在服务器上使用网络浏览器......效果不佳。我想知道是否有人有解决方案允许我使用此应用程序而无需使用Web浏览器进行身份验证。

编辑:在服务协议事项上遇到困难

所以...我在目前的申请中有这个以获得认证......

     /** Authorizes the installed application to access user's protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
        JSON_FACTORY, new InputStreamReader(
            extractanalyticsgoogleapi.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=analytics "
          + "into analytics-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY)).setDataStoreFactory(
        dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

而且我不确定我将把服务Acc代码放到哪里

1 个答案:

答案 0 :(得分:2)

您要做的是设置有权访问您的Google Analytics数据的service account。 这样,您的服务器代码就可以访问您的Google Analytics信息。

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.jackson2.JacksonFactory;
import com.google.api.services.analytics.AnalyticsScopes;

// ...

String emailAddress = "123456789000-abc123def456@developer.gserviceaccount.com";
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(emailAddress)
    .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12"))
    .setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
    .build();