I have a consumer google account of the form "[email protected]" for which I have a service account of the form "[email protected]". I am trying to use the private key generated for this service account to generate an access token and then may be edit or view the calendar associated with "[email protected]". The authentication code:
String emailAddress = "[email protected]";
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
File file = new File("path to .p12 file");
HttpTransport httpTransport = GoogleNetHttpTransport
.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(file)
.setServiceAccountScopes(
Collections.singleton("https://www.googleapis.com/auth/calendar"))
.setServiceAccountUser("[email protected]")
.build();
String accessToken = credential.getAccessToken();
But the access token generated is null. The service account has edit permissions. The program is able to access the .p12 file. Any cue as to where am I going wrong?
I think you've misunderstood how Service Accounts work. Impersonating a user only works within a Google Apps domain. You can't use a Service Account to impersonate a gmail account.