My studying notebook

2014/01/16

ASP.NET MVC 4 using Google Calendar API via OAuth 2

1/16/2014 10:26:00 PM Posted by Unknown , , , , , 11 comments

Scenario

It's more easily to log in your application via OAuth and OpenID provider in  ASP.NET MVC 4 now. Microsoft has few build-in client for Microsoft, Twitter, Facebook, Google. The Google client is based on OpenID and not OAuth. That's mean you can not access Google Data API. There is a post talk about how to implement custom Google client with Google+ login via OAuth in ASP.NET MVC 4. (http://www.beabigrockstar.com/google-signin-for-asp-net-mvc/ Google+ Signin for ASP.NET MVC - Be A Big Rockstar )

Register a Client ID for web application in Google Developer Console

In order to access Google Data API for web application. You need to register a Client ID to get Client ID an Client Secret for setting in your application.


As above snapshot show, you need to assign redirect URIs for grap OAuth access token callback also. Here we setup Rirect URIs as

 http://localhost:57271/Account/ExternalLoginCallback 

Google Client Library for .NET

The Google APIs Client Library for .NET is generic .NET runtime client for Google Services. The library supports OAuth2.0 authentication, and is able to generate strongly typed client libraries for Discovery-based services.
Google Client library is a higher level library for using Google Data API. You can download beta version from Nuget in visual studio.

 https://www.nuget.org/packages/Google.Apis.Calendar.v3/ 
It's more difficult to handle Google Client Library for .NET with few documents and sample now. Here, just using Google.Apis.Calendar.v3.Data namespace to our strong type class for data binding in deserialize object from API response.

        private Event GoogleEventHandle(string token, string method, string requestURL, string requestBody = null)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.KeepAlive = true;
            request.ContentType = "application/json";
            request.Method = method;
            request.Headers.Add("Authorization", "Bearer " + token);

            if(requestBody != null)
            {
                Stream ws = request.GetRequestStream();
                using (var streamWriter = new StreamWriter(ws, new UTF8Encoding(false)))
                {
                    streamWriter.Write(requestBody);
                }
            }

            var response = request.GetResponse();
            var stream = new StreamReader(response.GetResponseStream());

            var googleEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(stream.ReadToEnd().Trim());

            return googleEvent;  
        }

        private Event CreateGoogleEvent(string token, string calendarId, string requestBody)
        {
            var requestURL = string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events", calendarId);
            return GoogleEventHandle(token, "POST", requestURL, requestBody);              
        }
Above is methods how we are accessing Google Calendar v3 API via webrequest.

MVC view

Now, we are be able to access Google Calendar API via OAuth. Nest step, we will create a simple CRUD UI by AngularJS. 

The Google Event we created and save to database also.

You should choose which calendar you want to create a new event.

You can modify event anytime you want.

What you will see in your Google Calendar.

Summary

  1. It a good topic to discuss where do you store the Access token from Google OAuth. Session or database?
  2. Google Client Library for .NET is a convienient library to access Google Data API with OAuth include. It's still in developing and i hope that there have more documents and samples to show how to use it.

Reference

Github repository

As always, all source code can be found in Github in the repository
 https://github.com/cage1016/ASPNETMvc4GoogleOAuth

11 comments:

  1. work like a charm.

    Awesome solution. simple and did the job.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. your github solution was worked.but does not create a event and not sync my google calender

    ReplyDelete
  4. Not suitable for me because your github solution was worked.but does not create a event and not sync my google calender

    ReplyDelete
  5. Impressive. Your story always bring hope and new energy. Keep up the good work.
    officialPanda

    ReplyDelete
  6. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    cyber security certification malaysia

    ReplyDelete