Search code examples
oauth-2.0google-apigoogle-oauthgoogle-apps

Not able to extract access token google service account


I have a consumer google account of the form "me@gmail.com" for which I have a service account of the form "Something@developer.gserviceaccount.com". 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 "me@gmail.com". The authentication code:

String emailAddress = "something@developer.gserviceaccount.com";
    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("me@gmail.com")
            .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?


Solution

  • 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.