This article describes how to implement Google OAuth in ASP.NET web apps.
Introduction Nowadays, security is a major concern for every service provider like Google, Yahoo, Microsoft etc. and that’s why each service provider who is providing some external service to another app is following the protocol defined by OAuth. I am going to describe here how to implement Google OAuth in an ASP.NET app. Prerequisites You should have a basic knowledge of,
Steps for implementing For implementing OAuth, we will have to follow this series of steps.
Don’t worry about the above steps. I am going to explain these in detail, along with a proper demo. Let’s Start.
Run the project. Open the Google developer console. Go to Credentials. Click on "Edit OAuth client". Now, copy the project URL and paste in textbox of authorized JavaScript origin. Keep it open. Open the googlecallback.aspx in browser and copy the URL. Paste the url in authorized redirect uri. Now, we have completed the settings of the project on Google developer console. It's time to get back to our implementation part.
So, let's write the code for authorizing user. Copy the below code in authorize.aspx.cs under partial class -
Now, we have web page which will authorize the user. Let’s create the page for Saving the data in database after successful authorization. So we will have to write code in GoogleCallBack.aspx.cs
So, let’s write the code.Copy the below code in GoogleCallBack.aspx.cs under namespace.
Testing Implementation Perform the following steps.
Cool, Isn’t It? Now, we have refresh token so the next question will be how to use the refresh token to get the access token?
Now, run the project and navigate to GetEmail.aspx. Enter the user id and see the page in action. Finally, We have successfully implemented the OAth2.0 authorization for Google. Interesting Points Have you noticed, we are getting only email id. So, what is the thing which is saying to Google that the system wants only email id - the scope is the thing that we send at the time of authorization to Google to let Google know that the requesting system wants this type of service. You can also send multiple scopes to get the multiple service e.g - Google contacts, Google calendar etc. Want to know how we can get the Google Calendar, Google Contacts or how we can upload the file on GoogleDrive? Let's wait for my next article.
References
Getting Started with ASP.NET 4.5 Web Forms and Visual Studio 2013