Is it possible to use a service account to access the Google Admin Report SDK?
I have a very basic example I am trying to run and I always get a 400 error returned. I have validated the key and service ID are correct and I have even delegated authority to this service account. Is this just not possible? Anyone have any ideas?
PrivateKey serviceAcountPrivateKey = null;
try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("insta2.p12")) {
serviceAcountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore(
SecurityUtils.getPkcs12KeyStore(), resourceAsStream, "notasecret",
"privatekey", "notasecret");
} catch (IOException | GeneralSecurityException e) {
throw new RuntimeException("Error loading private key", e);
}
try {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("[email protected]")
.setServiceAccountPrivateKey(serviceAcountPrivateKey)
.setServiceAccountScopes(
Arrays.asList(
ReportsScopes.ADMIN_REPORTS_USAGE_READONLY,
ReportsScopes.ADMIN_REPORTS_AUDIT_READONLY))
.build();
Reports service = new Reports.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("APP_NAME_BLOCKED")
.build();
service.activities().list("all", "admin").execute();
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("Error init google", e);
}
The error I get back is the following:
{ "code" : 401, "errors" : [ { "domain" : "global", "location" : "Authorization", "locationType" : "header", "message" : "Access denied. You are not authorized to read activity records.", "reason" : "authError" } ], "message" : "Access denied. You are not authorized to read activity records." }
For all of those wondering, if you do not use the call
.setServiceAccountUser("admins email address")
on the GoogleCredential object then this will fail as above. It is a little confusing as the service account on it's own does not have permission to access the reports, but it does have the ability to assume the role of an account that does...