来自 App Engine 的 Analytics API,AppIdentityCredential 权限不足

Analytics API from app engine with AppIdentityCredential insufficient permissions

我正在尝试从我的 java 应用引擎模块点击 Google 分析 API

我有以下代码来检索凭据。

public HttpRequestInitializer getCredentials() throws GeneralSecurityException, IOException {

    HttpRequestInitializer httpRequestInitializer;

    if (com.google.appengine.api.utils.SystemProperty.environment.value() == com.google.appengine.api.utils.SystemProperty.Environment.Value.Development) {

        String certificate = "/token.p12";
        File privateKey = null;

        try {
            privateKey = new File(getClass().getResource(certificate).toURI());
        } catch (URISyntaxException e) {
            log.log(Level.SEVERE, e.getMessage(), e);
        }

        httpRequestInitializer = new GoogleCredential.Builder()
                .setTransport(new NetHttpTransport())
                .setJsonFactory(new JacksonFactory())
                .setServiceAccountId("XXXX@developer.gserviceaccount.com")
                .setServiceAccountPrivateKeyFromP12File(privateKey)
                .setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
                .build();

    } else {

        httpRequestInitializer = new AppIdentityCredential(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY));

    }

    return httpRequestInitializer;
}

我已经在云开发控制台中为项目启用了分析 api。在 Google 分析中,我已授予服务帐户读取权限。 Google 分析使用与我用于 google 云相同的 google 帐户。

无论如何,当使用 App Engine 开发服务器时,此代码有效,我可以点击 api(使用客户端库)。但是,当来自 App Engine 本身的 运行 并且它使用 AppIdentityCredential 时,我在尝试点击 API.

时遇到以下异常
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403         OK
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "User does not have any Google Analytics account.",
"reason" : "insufficientPermissions"
} ],
"message" : "User does not have any Google Analytics account."
}

我假设 AppIdentityCredential 验证为拥有 app 引擎项目的用户,但我猜它不是?

我想使用 AppIdentityCredential,因为据我所知,建议将其用于生产实例。

如何使用 AppIdentityCredential 并使用它访问分析 api

嗯,好的,我明白了。

App Engine 项目绑定到 PROJECTNAME@appspot.gserviceaccount.com 的 identity/account。在分析设置中授予此帐户访问权限允许应用引擎代码使用 AppIdentityCredential

访问它