Alistair
Alistair

Reputation: 1979

Analytics API from app engine with AppIdentityCredential insufficient permissions

I am attempting to hit Google analytics API from my java app engine module.

I have the following code to retrieve the credential.

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("[email protected]")
                .setServiceAccountPrivateKeyFromP12File(privateKey)
                .setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
                .build();

    } else {

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

    }

    return httpRequestInitializer;
}

I have enabled the analytics api for the project in the cloud dev console. In Google analytics I have given the service account read access. Google analytics is using the same google account as I am using for google cloud.

Anyway, when using the app engine dev server this code works and I can hit the api (using the client library). However, when run from app engine itself and it uses AppIdentityCredential I am getting the following exception when attempting to hit the 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."
}

I would assume that AppIdentityCredential authenticates as the user who owns the app engine project, but I guess it doesn't?

I would like to use AppIdentityCredential as I understand that this is recommended for production instances.

How can I use AppIdentityCredential and access the analytics api with it?

Upvotes: 1

Views: 246

Answers (1)

Alistair
Alistair

Reputation: 1979

Uh ok I figured it out.

The app engine project is tied to the identity/account of [email protected] . Giving this account access in analytics settings allows the app engine code to access it using AppIdentityCredential

Upvotes: 2

Related Questions