Not able to extract access token google service account

169 views Asked by At

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?

2

There are 2 answers

5
pinoyyid On BEST ANSWER

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.

0
omerio On

I doubt you get an access token when using a service account. If you were using OAuth2 dance and prompting the user for permissions then yes can get an access token, etc.. This is the correct way to initialize the API Calendar instance from a Google Credential object:

import com.google.api.services.calendar.Calendar;
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, null)
  .setHttpRequestInitializer(credential).build();

You can then use the Calendar instance to make API calls. More information can be found here: https://developers.google.com/admin-sdk/directory/v1/guides/delegation https://developers.google.com/google-apps/calendar/quickstart/java