2

Мне удалось получить доступ к API календаря Google с помощью учебника .NET Quickstart, и он отлично поработал!Доступ к API календаря Google с использованием проверки подлинности учетной записи службы

Проблема с этим учебником заключается в том, что он использует Open Authentication or OAuth2. Я хотел бы сделать то же самое, используя Service Account Authentication.

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

Может кто-нибудь дать мне пример того, как я могу получить доступ к календарю с помощью учетной записи службы ключевого файла?

Я также попытался использовать Google Calendar API Authentication with C# учебник и не смог его выполнить.

ответ

3

Мне интересно, почему ваша первая попытка с учетной записью службы учебника не работает. Что случилось? Была ли ошибка?

Помните, что учетные записи службы поддержки не являются таковыми. У учетной записи службы есть учетная запись календаря Google, поэтому, если вы пытаетесь прочитать один из ваших личных календарей, вам придется поделиться им с учетной записью службы.

Вот еще один пример использования 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", 
     }); 
+1

Это (и ваш блог) был большим подспорьем для меня. Наконец, приложение выполнило аутентификацию в Google Calendar API с помощью учетной записи службы. Благодаря! – dybzon

2

Попробуйте это. Сначала Create a service account, который можно найти в консоли Google Dev.

Для справки об осуществлении см. DalmTo's blogpost о том, как использовать учетные записи служб здесь.

Вот отрывок:

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; 
} 
1

посещают эту ссылку имеют полную проверку подлинности учетной записи Google службы рабочего проекта с календарем Google метод вставки события вы должны изменить свой JSon секретный ключ и ваши учетные данные только https://github.com/CodeForget/Google-Service-Account-Authentication

here json key file othentication as well p12 authentication both

ServiceAccountAuthentication. cs

using Google.Apis.Calendar.v3; 
using Google.Apis.Auth.OAuth2; 
using Google.Apis.Services; 
using System; 
using System.IO; 
using System.Security.Cryptography.X509Certificates; 
using Google.Apis.Calendar.v3.Data; 

namespace GoogleSamplecSharpSample.Calendarv3.Auth 
{ 



    public static class ServiceAccountExample 
    { 

     /// <summary> 
     /// Authenticating to Google calender using a Service account 
     /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount 
     /// </summary> 
     /// Both param pass from webform1.aspx page on page load 
     /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com/projectselector/iam-admin/serviceaccounts </param> 
     /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com/projectselector/iam-admin/serviceaccounts </param> 
     /// <returns>AnalyticsService used to make requests against the Analytics API</returns> 

     public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes) 
     { 
      try 
      { 
       if (string.IsNullOrEmpty(serviceAccountCredentialFilePath)) 
        throw new Exception("Path to the service account credentials file is required."); 
       if (!File.Exists(serviceAccountCredentialFilePath)) 
        throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath); 
       if (string.IsNullOrEmpty(serviceAccountEmail)) 
        throw new Exception("ServiceAccountEmail is required."); 

       // For Json file 
       if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json") 
       { 
        GoogleCredential credential; 
        //using(FileStream stream = File.Open(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read, FileShare.None)) 


        using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)) 
        { 
         credential = GoogleCredential.FromStream(stream) 
          .CreateScoped(scopes).CreateWithUser("[email protected]");//put a email address from which you want to send calendar its like (calendar by xyz user) 
        } 

        // Create the Calendar service. 
        return new CalendarService(new BaseClientService.Initializer() 
        { 
         HttpClientInitializer = credential, 
         ApplicationName = "Calendar_Appointment event Using Service Account Authentication", 
        }); 
       } 
       else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12") 
       { // If its a P12 file 

        var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); 
        var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) 
        { 
         Scopes = scopes 
        }.FromCertificate(certificate)); 

        // Create the Calendar service. 
        return new CalendarService(new BaseClientService.Initializer() 
        { 
         HttpClientInitializer = credential, 
         ApplicationName = "Calendar_Appointment event Using Service Account Authentication", 

        }); 
       } 
       else 
       { 
        throw new Exception("Something Wrong With Service accounts credentials."); 
       } 

      } 
      catch (Exception ex) 
      {     
       throw new Exception("Create_Service_Account_Calendar_Failed", ex); 
      } 
     } 


    } 
} 

добавить webform.aspx и поместить этот код на webform.aspx.cs

using System; 
using Google.Apis.Calendar.v3; 
using GoogleSamplecSharpSample.Calendarv3.Auth; 
using Google.Apis.Calendar.v3.Data; 

namespace CalendarServerToServerApi 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 
     // create event which you want to set using service account authentication 
     Event myEvent = new Event 
     { 
      Summary = "Visa Counselling", 
      Location = "Gurgaon sector 57", 
      Start = new EventDateTime() 
      { 
       DateTime = new DateTime(2017, 10, 4, 2, 0, 0), 
       TimeZone = "(GMT+05:30) India Standard Time" 
      }, 
      End = new EventDateTime() 
      { 
       DateTime = new DateTime(2017, 10, 4, 2, 30, 0), 
       TimeZone = "(GMT+05:30) India Standard Time" 
      } 
      //, 
      // Recurrence = new String[] { 
      //"RRULE:FREQ=WEEKLY;BYDAY=MO" 
      //} 
      //, 
      // Attendees = new List<EventAttendee>() 
      // { 
      // new EventAttendee() { Email = "[email protected]" } 
      //} 
     }; 

     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 


     public void Authenticate(object o, EventArgs e) 
     { 
      string[] scopes = new string[] { 
    CalendarService.Scope.Calendar //, // Manage your calendars 
    //CalendarService.Scope.CalendarReadonly // View your Calendars 
}; 
      string cal_user = "[email protected]"; //your CalendarID On which you want to put events 
      //you get your calender id "https://calendar.google.com/calendar" 
      //go to setting >>calenders tab >> select calendar >>Under calender Detailes at Calendar Address: 

      string filePath = Server.MapPath("~/Key/key.json"); 
      var service = ServiceAccountExample.AuthenticateServiceAccount("[email protected]", filePath, scopes); 
      //"[email protected]" this is your service account email id replace with your service account emailID you got it . 
      //when you create service account https://console.developers.google.com/projectselector/iam-admin/serviceaccounts 

      insert(service, cal_user, myEvent); 

     } 



     public static Event insert(CalendarService service, string id, Event myEvent) 
     { 
      try 
      { 
       return service.Events.Insert(myEvent, id).Execute(); 

      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
       return null; 
      } 
     } 


    } 
} 
Смежные вопросы