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 , , , , , 35 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

35 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. Gaining Python certifications will validate your skills and advance your career.
    python certification

    ReplyDelete
  6. I was very happy to find this site. I really enjoyed reading this article today and think it might be one of the best articles I have read so far. I wanted to thank you for this excellent reading !! I really enjoy every part and have bookmarked you to see the new things you post. Well done for this excellent article. Please keep this work of the same quality.
    Data Science Course in Bangalore

    ReplyDelete
  7. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    Data Science Course in Bangalore

    ReplyDelete
  8. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    best data science courses in bangalore

    ReplyDelete
  9. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    data scientist course in bangalore

    ReplyDelete
  10. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    data analytics course in bangalore

    ReplyDelete
  11. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    data analytics courses in bangalore

    ReplyDelete
  12. I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
    Data Science Training in Chennai

    ReplyDelete
  13. I am a new user of this site, so here I saw several articles and posts published on this site, I am more interested in some of them, hope you will provide more information on these topics in your next articles.
    data analytics training in bangalore

    ReplyDelete
  14. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    data science certification in bangalore

    ReplyDelete
  15. Thank you so much for ding the impressive job here, everyone will surely like your post.
    business analytics course

    ReplyDelete
  16. Impressive. Your story always bring hope and new energy. Keep up the good work.
    data science training

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

    ReplyDelete
  18. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    fun138

    ReplyDelete
  19. Great Post Thanks For Sharing, have a look at it for free digital marketing training..

    digital marketing training in hyderabad
    digital marketing course in hyderabad

    ReplyDelete
  20. Welcome to CapturedCurrentNews – Latest & Breaking India News 2021
    Hello Friends My Name Anthony Morris.latest and breaking news drupepower.com

    ReplyDelete
  21. Sir apki website par original content diya jata ha muje apke dyra di gyi jankari bhout acchi lagi agar ap moje yh bta ske ki agla airtical kab ayega your very very knowledge full airtical thanks sir:
    short story in hindi motivational

    ReplyDelete
  22. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us.
    data science training

    ReplyDelete