Google Analytics 3.0认证流程 [英] Google Analytics 3.0 auth flow

查看:194
本文介绍了Google Analytics 3.0认证流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:最初,这个问题询问我如何仅使用我的API密钥对Google Analytics API进行身份验证。正如 vlatko指出,这是不可能的。现在我只关注让OAuth2工作。当我有机会并会更新问题时,我会尝试vlatko的建议。与此同时,随时提供答案与任何你认为我失踪。






原始问题:



我正在尝试向Google Analytics API发出请求。我正在浏览试图复制的 Hello Analytics 教程步骤。无论我尝试什么,我都无法成功进行身份验证。



本教程提供以下内容:


打开您创建的名为 HelloAnalyticsApi.java 的文件并添加
以下方法:

 私有静态分析initializeAnalytics()抛出异常{
//授权。
凭证的凭证= OAuth2Native.authorize(
HTTP_TRANSPORT,JSON_FACTORY,新LocalServerReceiver(),
Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY));

//设置并返回Google Analytics API客户端。
返回Analytics.builder(HTTP_TRANSPORT,JSON_FACTORY)
.setApplicationName( 谷歌 - 分析 - 你好,分析-API-样本)
.setHttpRequestInitializer(凭证)
.build( );
}

当用户遇到此脚本时,应用程序将尝试
打开默认浏览器并将用户导航到
google.com上托管的网址。此时,系统会提示用户登录,
授予应用程序访问其数据的权限。一旦被授予,
应用程序将尝试从浏览器窗口读取代码,然后
关闭窗口。




<不同之处在于我试图用一个servlet应用程序来做到这一点,我想用一个API密钥(而不是OAuth 2.0客户端ID)使用简单的API访问。我知道建议使用OAuth 2.0,但我只需访问我拥有的数据并希望简化技术要求。我在此页面上做出了这一决定,其中说:


API密钥是您使用控制台生成的唯一密钥。当
时,您的应用程序需要调用在此项目中启用的API,
应用程序将此密钥作为键传递给所有API请求= {API_key}
参数。使用此密钥不需要任何用户操作或
同意,不授予对任何帐户信息的访问权限,也不会授权使用



如果您只调用不需要用户数据的API,例如
Google Custom Search API,那么API键可能更简单,只需
即可。但是,如果您的应用程序已经使用OAuth 2.0
访问令牌,则不需要生成API密钥。在
的事实中,如果OAuth 2.0访问令牌已经与相应的项目相关联,则Google会忽略传递的API密钥。


我找不到很多使用API​​密钥的验证流程代码示例 - 我发现的大部分内容都显示了使用客户端ID与下载的.p12文件,例如 GoogleCredential javadoc。我能找到的一个示例应用程序是Google的 Books Sample app。无论如何,这是我的尝试(模仿教程中的第一个请求,它从管理API获取帐户列表):

  Analytics analytics = 
新的Analytics.Builder(httpTransport,jsonFactory,null)
.setApplicationName(Dev API Access)
.build();
Management.Accounts.List list =
analytics.management()。accounts()。list()。setKey(apiKey);
Accounts accounts = list.execute();

其中开发API访问是我的API控制台仪表板中的名称字段。 API密钥是一个限制于我的IP地址的服务器密钥。这会失败并返回以下回应:

  401未授权
{
code:401,
错误:[
{
domain:global,
location:Authorization,
locationType:header,
message:需要登录,
reason:required
}
],
消息:需要登录
}

我也试过这个:

 分析分析= 
新Analytics.Builder(httpTransport,jsonFactory,NULL)
.setApplicationName( 开发API访问)
.setGoogleClientRequestInitializer(新AnalyticsRequestInitializer(apiKey ))
.build();

Management.Accounts.List list = analytics.management()。accounts()。list();
Accounts accounts = list.execute();

其中显示相同的错误。我在这里做错了什么?分析呼叫需要OAuth2吗?如果是这样,为什么只使用Books Sample应用程序中的API密钥工作?






继续前进,无论如何尝试OAuth2 - 我创建了一个客户端ID并下载了.p12私钥文件。但是我也无法做到这一点。以下是我试过的:

 凭证凭证= 
新GoogleCredential.Builder()
.setTransport(httpTransport )
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
.setServiceAccountPrivateKeyFromP12File(新文件(p12FilePath))
.setServiceAccountUser( serviceAccountUser)
.build();

Analytics分析=
新的Analytics.Builder(httpTransport,jsonFactory,凭证)
.setApplicationName(Dev API Access)
.build();

Management.Accounts.List list = analytics.management()。accounts()。list();
Accounts accounts = list.execute();

其中 serviceAccountId 是电子邮件的电子邮件地址拥有该项目的Google帐户和 serviceAccountUser 是生成的客户端ID上列出的电子邮件地址。这会失败,如下所示:

  400错误请求
{
错误:invalid_grant
}

无效授权是什么意思,以及如何成功进行身份验证为了回答你的第一个问题:一般来说,OAuth2.0用于授权访问用户的私人数据,因此需要获得用户的同意并获得访问令牌。然而,就Google Books API而言,如果您正在访问公共数据,则不需要最终用户同意,因此API密钥就足够了。如果您尝试使用Books API访问非公开数据,您仍然需要OAuth2令牌。



您的情况的好消息是即使使用OAuth2,也可以绕过用户参与并使用服务帐户简化流程 - 假设您的应用程序可以访问API。有一种方法可以设置Analytics API,详见此处 a>(检查服务帐户部分中的步骤)。我认为你在 Credential 构建器的正确轨道上,但我认为你不需要在那里设置服务帐户用户,因为你没有做任何用户模拟。


EDIT: Originally this question asked how I could authenticate with the Google Analytics API using only my API key. As vlatko pointed out, this isn't possible. Now I'm just focused on getting OAuth2 to work. I will be trying vlatko's suggestions when I get a chance and will update the question. In the meantime, feel free to contribute answers with anything you think I'm missing.


ORIGINAL QUESTION:

I'm trying to make requests to the Google Analytics API. I'm walking through the Hello Analytics tutorial trying to replicate the steps. Whatever I try, I can't seem to authenticate succesfully.

The tutorial says the following:

Open the file you created named HelloAnalyticsApi.java and add the following method:

private static Analytics initializeAnalytics() throws Exception {
    // Authorization.
    Credential credential = OAuth2Native.authorize(
        HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(),
        Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY));

    // Set up and return Google Analytics API client.
    return Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
        .setApplicationName("Google-Analytics-Hello-Analytics-API-Sample")
        .setHttpRequestInitializer(credential)
        .build();
  }

When a user encounters this script, the application will attempt to open the default browser and navigate the user to a URL hosted on google.com. At this point, the user will be prompted to login and grant the application access to their data. Once granted, the application will attempt to read a code from the browser window, then close the window.

The difference is that I'm trying to do this with a servlet application, and I want to use simple API access with an API key (rather than an OAuth 2.0 client ID). I know that OAuth 2.0 is recommended, but I only need to access data that I own and want to simplify the technical requirements. I based this decision on this page, which says:

An API key is a unique key that you generate using the Console. When your application needs to call an API that's enabled in this project, the application passes this key into all API requests as a key={API_key} parameter. Use of this key does not require any user action or consent, does not grant access to any account information, and is not used for authorization.

If you are only calling APIs that do not require user data, such as the Google Custom Search API, then API keys may be simpler to implement. However, if your application already uses an OAuth 2.0 access token, then there is no need to generate an API key as well. In fact, Google ignores passed API keys if an OAuth 2.0 access token is already associated with the corresponding project.

I can't find many code examples of auth flow just using the API key - most everything I've found shows using the client ID with the downloaded .p12 file, for example the GoogleCredential javadoc. The one example application I could find was Google's Books Sample app. Anyway, here's what I tried (mimicking the first request in the tutorial, which gets a list of the accounts from the management API):

Analytics analytics =
        new Analytics.Builder(httpTransport, jsonFactory, null)
        .setApplicationName("Dev API Access")
        .build();
Management.Accounts.List list =
        analytics.management().accounts().list().setKey(apiKey);
Accounts accounts = list.execute();

Where "Dev API Access" is the "Name" field in my API console dashboard. The API key is a server key restricted to my IP address. This fails with the following response:

401 Unauthorized
{
  "code": 401,
  "errors": [
    {
      "domain": "global",
      "location": "Authorization",
      "locationType": "header",
      "message": "Login Required",
      "reason": "required"
    }
  ],
  "message": "Login Required"
}

I also tried this:

Analytics analytics =
        new Analytics.Builder(httpTransport, jsonFactory, null)
        .setApplicationName("Dev API Access")
        .setGoogleClientRequestInitializer(new AnalyticsRequestInitializer(apiKey))
        .build();

Management.Accounts.List list = analytics.management().accounts().list();
Accounts accounts = list.execute();

Which shows the same error. What am I doing wrong here? Is OAuth2 required for analytics calls? If so, why does just using the API key work in the Books Sample app?


Moving on, I went ahead and tried OAuth2 anyway - I created a client ID and downloaded the .p12 private key file. But I couldn't get that working either. Here's what I tried:

Credential credential =
        new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(serviceAccountId)
        .setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
        .setServiceAccountPrivateKeyFromP12File(new File(p12FilePath))
        .setServiceAccountUser(serviceAccountUser)
        .build();

Analytics analytics =
        new Analytics.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("Dev API Access")
        .build();

Management.Accounts.List list = analytics.management().accounts().list();
Accounts accounts = list.execute();

Where serviceAccountId is the email address of the Google account owning the project and serviceAccountUser is the email address listed on the generated client ID. This fails with the following:

400 Bad Request
{
  "error": "invalid_grant"
}

What does "invalid grant" mean, and how do I successfully authenticate (ideally without OAuth2)?

解决方案

To answer your first question: in general, OAuth2.0 is used for authorized access to user's private data, so getting user consent and obtaining an access token is required. In the case with Google Books API, however, if you're accessing public data, there is no need for end user consent so an API key is sufficient. If you try accessing non public data with the Books API, you'll still need an OAuth2 token.

The good news for your case is that even with OAuth2, you can bypass user involvement and streamline your flow with Service Accounts - assuming your application has access to the API. There is a way to set that up for the Analytics API, explained here (check the steps in the Service Accounts section). I think you are on the right track with your Credential builder, but I don't think you need to set the service account user in there, since you are not doing any user impersonation.

这篇关于Google Analytics 3.0认证流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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