Tuesday, 20 December 2016

How to login with gmail in Asp.net MVC



Video Tutorial:

Download Full Source Code:

Download here


Introduction:
 Here I will explain how to login with Gmail account in Asp.net MVC.  Returned data will be in JSON format and you can save that data in your database table.
Description:
So now we start.
Step1: Firstly we need to get Client ID and Secret key from Google Developer website (https://developers.google.com/identity/sign-in/web/devconsole-project)
Step2: In this step we add two JavaScript files in Index.cshtml file

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

Step3: Create variables and function in Index.cshtml file as fallows

<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: '/category/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>

Step4: Add fallowing html in Index page

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

Output:  Run project and output as follows:


2 comments:

  1. Can you write java script method to log out and saving info of user to SQL Server table.

    ReplyDelete
    Replies
    1. I already write a function for saving data from Google API

      In my case i create GoogleLogin action method in Category controller and post data into this controller like this

      $.ajax({

      url: '/category/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"

      });

      Delete

Ads Inside Post