google-apigoogle-calendar-apigoogle-oauthgoogle-oauth-java-client

Cannot get access to Google Calendar API via Service Account


I'm trying to retrieve my own free/busy calendar via a simple POST call in Java, and I'm running into access errors. Basically I'm getting a 404, notFound error like so:

{
 "kind": "calendar#freeBusy",
 "timeMin": "2019-05-28T13:00:00.000Z",
 "timeMax": "2019-05-28T21:00:00.000Z",
 "calendars": {
  "me@mycompany.com": {
   "errors": [
    {
     "domain": "global",
     "reason": "notFound"
    }
   ],
   "busy": []
  }
 }
}

The code is fairly straightforward. I can get exactly what I need if I use a bearer token from the OAuth Playground, everything works just fine. Here's my relevant code:

        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(Objects.requireNonNull(classLoader.getResource("...a59.json")).getFile());

        GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream(file))
                .createScoped(CalendarScopes.all());

        credential.refreshToken();
        String accessToken = credential.getAccessToken();

The accessToken value I get back results in the response above.

For my service account, I have created it within a project that has the Calendar API enabled. I've also granted it the role of Project Owner so that it has full access to the settings in the project.

I'm sure this is something small and simple with my Service Account configuration, but I cannot for the life of me figure out what it is.


Solution

  • So I managed to figure this one out myself. Seems that my service account was setup correctly, but the permissions I added were not. For the record, here's what I wanted:

    1. Get read-only access to a calendar.
    2. Be able to retrieve the calendar of any user in my organization.

    I had created the service account, made sure it had Domain Wide Delegation authorization, added the Calendar and Admin APIs to my project that holds the service account, but I couldn't get it to work without adding my service account to the calendar per @Alex Baban's message above.

    I went back to the drawing board as adding this to a few dozen accounts wasn't an ideal solution, and then I found it. I had to add the following authorizations for my service account:

    Hopefully this helps someone else out in the future.