How to login with Google account API in Asp.net MVC - 5

This tutorial shows you how to build an ASP.NET MVC 5 web application that enables users to log in with credentials of Google account, and then integrate some of the functionality from Google account into your web application.

Introduction:

      In my previous article, we have seen How to login with Facebook in Asp.net MVC, Today in this article, I will explain how to login with Gmail account in Asp.net MVC.

Enable an Authentication sign in with Google and allow users to sign in with their Google account, you will need to register an application in Google Developers Console. After you have register the application you can use the Client ID and Client Secrete Key supplied by Google to register the Google Social login provider in your Asp.net MVC application

Ok, let’s start Asp.net MVC Google authentication

 

Fallow these steps in order to implement “Google Sign-in for your Asp.net MVC application”

Step1:  Create client Id and client secret

In first step create new project in Google Developers Console for use Google authentication service. Make sure you must have to login with your account.

Firstly click on ‘Create project’

 

 

 

In the ‘New project’ dialog, write you project name.

 

 

 

After giving your project name. Click on to ‘Create’ button to create your project.

In next step click on Google+ API link.

 

          

 

Next Click on ‘Enable’ button, by click on Enable button API will be enable

 

 

 

In next you must have to enter your credentials, by which you can use API in your project.

So Click on ‘Create Credentials’ and under it choose ‘OAuth client id

 

 

 

For configure consent screen click on it

 

 

Now you should enter your registered email id and project name, click to save button to save this.

 

 

 

Click on radio button ‘Web application’ and then enter your authorized redirect URLs.

You should enter your correct URL as in Visual Studio, go to properties of your project and then copy your URL.

Then click to ‘Create’ button.

 

 

After click on ‘Create’ button the client id and client secret will be generated. Now copy both client id and client secret from OAuth client popup

 

 

 

Now go to your project.

 

Step2: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty project > then click to ok

Step3: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Template "empty MVC Controller"> Add.

Here I have created a controller "HomeController"

 

Now we will add a view for Index action (which is already added in the home controller) where we will implement Gmail account authentication.

 

Step4: Add view for Index action.

 

Right Click on Action Method (here right click on Index action) > Add View > Enter View Name > Select "Empty" under Template dropdown > Check use a layout page > Add.

 

Write fallowing HTML code in your Index view

 

HTML Code:

 

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script type="text/javascript">
        var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
        var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
        var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
        var CLIENTID = '331417780027-lo2mtpg59b47v87alelkuv1o5889h78d.apps.googleusercontent.com';
        var REDIRECT = 'http://localhost:56623/Home/Index';
        var LOGOUT = 'http://localhost:56623/Home/Index';
        var TYPE = 'token';
        var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
        var acToken;
        var tokenType;
        var expiresIn;
        var user;
        var loggedIn = false;

        function login() {

            var win = window.open(_url, "windowname1", 'width=800, height=600');
            var pollTimer = window.setInterval(function () {
                try {
                    console.log(win.document.URL);
                    if (win.document.URL.indexOf(REDIRECT) != -1) {
                        window.clearInterval(pollTimer);
                        var url = win.document.URL;
                        acToken = gup(url, 'access_token');
                        tokenType = gup(url, 'token_type');
                        expiresIn = gup(url, 'expires_in');

                        win.close();
                        debugger;
                        validateToken(acToken);
                    }
                }
                catch (e) {

                }
            }, 500);
        }

        function gup(url, name) {
            namename = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\#&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(url);
            if (results == null)
                return "";
            else
                return results[1];
        }

        function validateToken(token) {

            getUserInfo();
            $.ajax(

                {

                    url: VALIDURL + token,
                    data: null,
                    success: function (responseText) {


                    },

                });

        }

        function getUserInfo() {


            $.ajax({

                url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
                data: null,
                success: function (resp) {
                    user = resp;
                    console.log(user);
                    $('#uname').html('Welcome ' + user.name);
                    $('#uemail').html('Email: ' + user.email)
                    $('#imgHolder').attr('src', user.picture);


                },


            }),

            $.ajax({

                url: '/Home/GoogleLogin/',

                type: 'POST',
                data: {
                    email: user.email,
                    name: user.name,
                    gender: user.gender,
                    lastname: user.lastname,
                    location: user.location
                },
                success: function () {
                    window.location.href = "/Home/Index/";
                },

                //dataType: "jsonp"

            });


        }

    </script>

</head>
<body>
    <div>
        <button class="button" id="GoogleLogin" onclick="login()" style="background-color:#e82121"><i class="fa fa-google-plus"></i> Sign in with Google</button>
        <div id="uname"></div>
        <div id="uemail"></div><br />
        <div><img id="imgHolder" style="height:120px;width:120px;" /></div>
    </div>
</body>
</html>

 

Step5: Add a method in HomeController

 

Add a method in the HomeController for get data from Index View

 

public void GoogleLogin(string email,string name, string gender,string lastname,string location)
        {
            //Write your code here to access these paramerters
           
        }

 

 

Step6: Run Application

We have done all steps. Now it’s time to run the application.