Search code examples
oauth-2.0google-calendar-apigoogle-oauthgoogle-contacts-apigoogle-api-dotnet-client

Is it possible to use AuthorizationCodeMvcApp for authorization in google contacts API access?


I am currently working on a web app where I sync the user's google contact list.

Currently I am able to sync the calendar just fine. Unfortunately the same approach doesn't seem feasible in the case of contacts.

Below was my approach for Calendars v3.

public async Task<ActionResult> Index(CancellationToken cancellationToken)
        {
            var user = User.Identity.GetUserId();
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
              AuthorizeAsync(user, cancellationToken);

            if (result.Credential != null)
            {
                CalendarService service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName = "Calendar API Sample",
                });
                var list = service.CalendarList.List().Execute();

                var calendar = list.Items.ElementAt(0);
                var events = service.Events.List(calendar.Id).Execute();



                foreach (var e in events.Items)
                {
                    try { 
                    EventLoot.data.Entities.Event model = new EventLoot.data.Entities.Event();
                    model.User_id = User.Identity.GetUserId();
                    model.Venue = e.Location != null ? e.Location : "" ;
                    model.Name = e.Summary;
                    model.Date = DateTime.Today;
                    model.start_date = e.Start.DateTime;
                    model.end_date = e.End.DateTime;
                    model.start_time = e.Start.DateTime.Value.TimeOfDay;
                    model.end_time = e.End.DateTime.Value.TimeOfDay;

                    dbcontext.Events.Add(model);
                    dbcontext.SaveChanges();
                    }
                    catch (Exception a)
                    {
                        Console.Write(a);
                    }
                }
                list.ToString();

                return View("index");
            }

I like this approach since the DataStore handles ensuring that I have a refresh token. Can this approach be adapted for Google Contacts as well? If so how?


Solution

  • Unfortunately Google Contacts supports the old GData protocol and the API doesn't have an equivalent library in the new Google APIs client library for .NET.

    But... I also have good news, take a look in this thread - How to create a ContactsService using Google Contact API v3 with OAuth v2 UserCredentials.
    You can add a new scope for the contacts API, "https://www.google.com/m8/feeds/" besides the calendar scope, and after the user finishes authenticating, you can use tokens stored in the DataStore to work with the GData API for Contacts.