masquerade75
masquerade75

Reputation: 11

Cannot impersonate service account to create calendar events

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.

Upvotes: 1

Views: 437

Answers (2)

Dmitry Kashcheiev
Dmitry Kashcheiev

Reputation: 92

In my case following works:

Make sure that you delegate domain-wide authority to ALL scopes requested in createScoped(...).

In the case above you use .createScoped(CalendarScopes.all()) that contains calendar.settings.readonly you do not provide authority for.

Replace it with:

.createScoped(ImmutableList.of(CalendarScopes.CALENDAR, CalendarScopes.CALENDAR_EVENTS))
.createDelegated("[email protected]")

Upvotes: 0

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117281

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();

Upvotes: 0

Related Questions