使用 App Engine 开发服务器向 Google API 声明身份

Asserting identity to Google APIs with App Engine development server

我在 App Engine 上有一个 Golang 应用程序 运行,我想调用 Analytics API 来处理一些指标。在 App Engine 和开发服务器上。

This page describes the overall procedure using a service account for server-to-server communication and getting an access token using OAuth2. I would like to avoid doing this myself so I found Google APIs for Go and the following that describes how to do it for App Engine.

我已将 App Engine 应用的服务帐户电子邮件添加到 Google Analytics 以获得读取权限。

我已经尝试使用 Query Explorer 进行查询,效果很好。我什至使用了此处的 API 查询 URI,其中包含正确的访问令牌并且工作正常。这适用于 cURL 或通过 App Engine 上的 urlfetch 调用它。

我需要的是在 App Engine 上以及在使用开发服务器时自动获取访问令牌。

此处是 URL 缩短器的示例,已将其修改为使用 Analytics API。

    client := http.Client{
            Transport: &oauth2.Transport{
                    Source: google.AppEngineTokenSource(c, analytics.AnalyticsScope),
                    Base: &urlfetch.Transport{Context: c},
            },
    }
    svc, err := analytics.New(&client)
    if err != nil {
            return nil, err
    }

    data, err := svc.Data.Ga.Get("...")

开发服务器的响应是401 Invalid Credentials, authError.

它应该像这样工作还是我遗漏了什么?

更新

这样,问题就解决了一半。当我传入服务帐户的电子邮件和 .pem 文件时,它现在使用开发服务器工作正常。但是,App Engine 中的同一个服务帐户不适用于上述代码!

googleapi: Error 403: User does not have any Google Analytics account., insufficientPermissions

User应该是我在开发服务器上已经成功使用的服务账号,所以我不太明白这个问题。 App Engine 和开发服务器上的代码完全相同。

Google Analytics 设置为具有读取权限,我使用只读 API。它已经在开发服务器上运行,所以应该没问题。

问题可能有什么不同?

可以在启动时向开发服务器提供必要的信息,如here

$ dev_appserver.py --appidentity_email_address email --appidentity_private_key_path file.pem

对于 App Engine,您不需要使用此服务帐户,而是使用应用程序名称的帐户:

app_name@appspot.gserviceaccount.com