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.
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",
});
Try this. First Create a service account which can be found in your Google Dev Console.
For reference on implementation, check DalmTo's blogpost on how to use Service Accounts here.
Here's a snippet:
var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
try{
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
//Create the service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample"
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
For anybody finding their way to this question but needing a NodeJS
solution, this is how you can log in with a service account that has domain-wide delegation permissions as a specific user:
const auth = new google.auth.JWT({ // use JWT instead of GoogleAuth
subject: "[email protected]", // specify subject (user whose context you want to operate in)
keyFile: "service-account-key.json",
scopes: [
"https://www.googleapis.com/auth/calendar.events",
"https://www.googleapis.com/auth/calendar.readonly"
],
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With