Implementing Google account authentication in ASP.NET MVC - Blogs
X
10Aug

Implementing Google account authentication in ASP.NET MVC

Implementation of Google OAuth in MVC application:

 

Step 1: Create a Google OAuth application

          To create it please follow the steps below:

  • Go to https://console.developers.google.com, login with your Gmail id.
  • Click on ‘Select a Project’ dropdown at left top of the page.
  • Click on ‘Create project’ button,
  • Enter project name and create project.
  • Click Credentials on the left navigation.
  • Click Create Credentials > OAuth ClientID, fill the form and submit.
  • Client ID and Client Secrete will be created on successful creation of application.
  • This will be used in Authorization process.

Step 2: Configuring your Google application

  • Login to  https://console.developers.google.com
  • Select your created application and click on edit.
  • Enter the ‘Authorized redirect URL’.
  • Click on ‘Save button.

    Now your application created and configured.

    Step 3: Creating visual studio application

  • Create empty Asp.Net MVC application and add controller.
  • In ‘Home View’ create one action link like below
    • @Html.ActionLink("Login Using Google", "")
  • In action method add redirect url, there user redirect to Google login URL,
  • Add controller and create callback function and add below code
    • Here we need to collect the Authorization code and Access token.
    • Sample code:

                    try

                    {

                        var url = Request.Url.Query;

                        if (url != "")

                        {

                            string queryString = url.ToString();

                            char[] delimiterChars = { '=' };

                            string[] words = queryString.Split(delimiterChars);

                            string code = words[1];

 

                            if (code != null)

                            {

                                //get the access token

                                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

                                webRequest.Method = "POST";

                                Parameters = "code=" + code + "&client_id=" + client_id + "&client_secret=" + client_sceret + "&redirect_uri=" + redirect_url + "&grant_type=authorization_code";

                                byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);

                                webRequest.ContentType = "application/x-www-form-urlencoded";

                                webRequest.ContentLength = byteArray.Length;

                                Stream postStream = webRequest.GetRequestStream();

                                // Add the post data to the web request

                                postStream.Write(byteArray, 0, byteArray.Length);

                                postStream.Close();

                                WebResponse response = webRequest.GetResponse();

                                postStream = response.GetResponseStream();

                                StreamReader reader = new StreamReader(postStream);

                                string responseFromServer = reader.ReadToEnd();

                                GoogleAccessToken serStatus = JsonConvert.DeserializeObject<GoogleAccessToken>(responseFromServer);

                                if (serStatus != null)

                                {

                                    string accessToken = string.Empty;

                                    accessToken = serStatus.access_token;

                                    Session["Token"] = accessToken;

                                    if (!string.IsNullOrEmpty(accessToken))

                                    {

                                      //call get user information function with access token as parameter

                                    }

                                }

                            }

                        }

                    }

                    catch (Exception ex)

                    {

                        return RedirectToAction("Index","Home");

                    }

            }

 

  • To get user information add below function

    try

                {

                    HttpClient client = new HttpClient();

                    var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;

                    client.CancelPendingRequests();

                    HttpResponseMessage output = client.GetAsync(urlProfile).Result;

                    if (output.IsSuccessStatusCode)

                    {

                        string outputData = output.Content.ReadAsStringAsync().Result;

                        serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);

                    }

                }

                catch (Exception ex)

                {

                    //catching the exception

                }

                return View(serStatus);

    Note: we need to create following model to Deserialize the json into object:

     

    public class GoogleAccessToken

           {

            public string access_token { get; set; }

            public string token_type { get; set; }

            public int expires_in { get; set; }

            public string id_token { get; set; }

            public string refresh_token { get; set; }

    }

     

    public class GoogleUserOutputData

           {

            public string id { get; set; }

            public string name { get; set; }

            public string given_name { get; set; }

            public string email { get; set; }

            public string picture { get; set; }

        }

     

  • Finally, we will add LogOff action to logoff user.

public ActionResult LogOff()
{

//Logout from application
    FormsAuthentication.SignOut();
    return Redirect(Url.Action("Index","Home"));

//Logout from google

            return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=";


}

 

Conclusion:     

We have discussed how to implement google oauth2 to secure our web application. The main advantage of google oauth2 is user no need to remember all of his/her account details, user can login using google credentials.

Related

LDAP Integration with Gitlab

If any organization has an LDAP directory service such as Active Directory, then GitLab can be confi...

Read More >

Microsoft Azure Webinars Registration- US

Date : 11th Feb 2016 | Day  : Thursday | Time : 11:30 AM EST | Duration : 1 HourREGISTER yourse...

Read More >

How to Host your Webpages on Google Drive

If you want to host your webpages quickly but don't have any web sever to host, then google driv...

Read More >

Starting with CSS Preprocessor

In this article we learn about, 1.What is CSS Preprocessor? 2.Installations 3.How to ...

Read More >

NAV – Connecting External SQL

This blog is intended to see how Microsoft Dynamics NAV (here onwards NAV) can be connected to exter...

Read More >

Creating a company and upload the packages through Rapid Start Services

In this blog we will see which tools can be used in Dynamics NAV to migrate data into the system and...

Read More >

It is Raining Gold. Time for the Celebrations.

Canarys has now achieved another Microsoft Gold Competency in “Collaboration and Content&rdquo...

Read More >

Introduction to Load Testing

 Well, before learning what is Load testing. Let us discuss briefly the performance testing.&nb...

Read More >

Azure Consulting Service

We are Microsoft Cloud Solution Providers (CSP) Canarys helps you achieve higher productivity, ...

Read More >

Share

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Text/HTML
Contact Us
  • *
  • *