1
votes

I'm trying to implement user impersonation with a google service account and have been having problems for a while, this is the code I am using in Java:

GoogleCredential credential = GoogleCredential
        .fromStream(TestGoogleCalendarEventCreate.class
            .getResourceAsStream("/ph3-rovigo-313910-6094af96ccfc.json"))
        .createScoped(CalendarScopes.all()).createDelegated("[email protected]");

When I try to read the events from a shared calendar, I receive the following authenication error:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized POST https://oauth2.googleapis.com/token

If I don't use impersonation, I am able to read the events but I can't invite attendees to newly created events. The service account has domain-wide authority enabled in a G-Suite domain as in the follwing screenshot. The clieint id is the client id of the service account user. Do I need other permission to be granted on any user?

enter image description here

Thanks a lot.

1

1 Answers

0
votes

I think you should be using setServiceAccountUser

 GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
      .setServiceAccountScopes(DirectoryScopes.ADMIN_DIRECTORY_USERS)
      .setServiceAccountUser(userEmail)
      .setServiceAccountPrivateKeyFromP12File(
          new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
      .build();