Access Google Calendar API using Service Account Authentication

I was able to access the Google Calendar API using the .NET Quickstart tutorial and it worked great!

The problem with that tutorial is that it uses Open Authentication or OAuth2. I will like to do the same using Service Account Authentication.

(https://support.google.com/googleapi/answer/6158857?hl=en)

Can someone give me an example of how I can access my calendar using a Service account key file?

I have tried also tried using Google Calendar API Authentication with C# tutorial and was not able to accomplish it.

Answer

I am curious as to why your first attempt with the service account tutorial didn’t work. What was wrong? Was there an error?

Remember service accounts are not you. The service account has its own Google calendar account, so if you are trying to read one of your “personal calendars”, it will not work. You are going to have to share your personal calendar with the service account.

Here is another example using the Json service account key file.

string[] scopes = new string[] { CalendarService.Scope.Calendar };
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
    credential = GoogleCredential.FromStream(stream)
                     .CreateScoped(scopes);
}

// Create the Calendar service.
var service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "Calendar Authentication Sample",
});