我正在尝试从我的 Java 应用引擎模块访问 Google Analytics 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 Analytics 中,我已授予服务帐户读取权限。 Google Analytics 使用的 Google 帐户与我用于 Google Cloud 的帐户相同。
无论如何,当使用应用程序引擎开发服务器时,此代码可以工作,并且我可以访问 api(使用客户端库)。但是,当从应用程序引擎本身运行并且它使用 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
?
最佳答案
嗯,好吧,我明白了。
应用引擎项目与 PROJECTNAME@appspot.gserviceaccount.com 的身份/帐户绑定(bind)。在分析设置中授予此帐户访问权限允许应用程序引擎代码使用 AppIdentityCredential 访问它
关于java - 来自应用程序引擎的分析 API AppIdentityCredential 权限不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067475/