Google Calendar API Service Account Error

Here are the steps to follow to make this work:

Enable Domain-Wide Delegation in your service account

1 – Provide calendar scopes to your service account

  • Go to https://admin.google.com/ and login with G Suite account.
  • Go to Security -> API Controls -> Domain-wide Delegation
  • Add new => Set the client ID of your service account (The one that’s only numbers)
  • Set the following scopes: https://www.googleapis.com/auth/calendar,https://www.googleapis.com/auth/calendar.events,https://www.googleapis.com/auth/admin.directory.resource.calendar

2 – Your user needs to have the role Service Account Token Creator

  • Go to https://console.cloud.google.com/iam-admin then
  • Select your project and go to IAM in the left menu.
  • Select the account that you will use to impersonate
  • Click on edit
  • Add role Service Account Token Creator
  • Enable domain delegation for the account according to https://developers.google.com/admin-sdk/directory/v1/guides/delegation, section To enable G Suite domain-wide delegation, follow these steps.

3 – Create a Calendar in the account that you will impersonate

Service accounts don’t have calendars so you have to create your own calendar

  • Login in https://calendar.google.com/ with the email that you want to own the calendar (I used a different account, not the same that I was going to impersonate, maybe it works using a calendar in the impersonated account)
  • Create a calendar
  • Share the calendar with the service account with permissions to modify and manage the calendar
  • Share the calendar with the account you will impersonate with permissions to modify and manage the calendar

Create google client

  • Authenticate your service account. (I used the JSON Key, I am not sure if other authentication works for this purpose)

Code sample: (I used PHP but I assume that other languages are very similar so you can use this as guideline)

Note that using some email for IMPERSONALIZATION is crucial. Otherwise, the 403 error will remain, use it for authentication, see the Maksym Kalin response for details.

$google_client = new Google_Client();
$google_client->setAuthConfig($LOCATION_OF_JSON_KEY);
$google_client->setAccessType( 'offline' );
$google_client->setSubject('EmailToImpersonate@SomeAddress.com');
$google_client->setApplicationName("YourApplicationName");
$google_client->setScopes([\Google_Service_Calendar::CALENDAR, \Google_Service_Calendar::CALENDAR_EVENTS]);

Create Event with people invited 🙂 and Enjoy!

Note: With this approach you can create events and invite people to it. Keep in mind the limits of the G Suite https://support.google.com/a/answer/2905486 so if you want to create many events you will need to have a pool of service accounts with a pool of calendars.

Leave a Comment