Wednesday, December 17, 2014

Login using Google Javascript API [Sample Code]

Latest Google Javascript API allow users to fetch their google profile information, circle details. Javscript API is not just limited to this, but it allow us to fetch and upload Google Drive file. Read more

In this tutorial we are utilizing Google+ Javascript API to fetch user Google+ Profile Details and Email address. It is purely OAuth2 Compatible login method and its secure.

Workflow is simple

  1. User Clicks on Login with Google Button on XYZ Website
  2. Google OAuth2 Popup opens and ask the user login to google account first.
  3. If Logged in, it shows the permissions that this website is requesting, then user accept this by pressing button Allow.
  4. Now the website receives the user information which are requested by the XYZ Website ( Login Scope )

Before you begin this tutorial, you actually need to setup a Project through Google Developer Console. You can follow google docs here.

Step 1: Create Project

Step 2: Set the Consent Screen details



Step 3: Create Web application Client Key and Secret



Now Client Key and Secret key successfully created.

Note: For javascript based login, we dont use Secret key, only Client Key is enough.


How to Google+ Javascript Login 

Add Google+ Javascript API Javascript Header
  <script type="text/javascript">
  (function() {
    var po = document.createElement('script');
    po.type = 'text/javascript'; po.async = true;
    po.src = 'https://plus.google.com/js/client:plusone.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(po, s);
  })();
  </script>
Add JQuery & Bootstrap for styling
    <!-- Bootstrap core CSS -->
  <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
  <link href="http://getbootstrap.com/examples/signin/signin.css" rel="stylesheet">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>


Complete HTML Body code for the Form and Google+ Button

   <div class="container">

      <form class="form-signin" role="form">
            <div id="status"></div>
        <h2 class="form-signin-heading">User Registration</h2>
        
        <label for="inputFname" class="sr-only">First Name</label>
            <input type="text" id="inputFullname" class="form-control" placeholder="First Name" required autofocus>
            
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required >
        
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
        
        <div class="row"> 
            <div class="col-md-6">
                <button class="btn btn-sm btn-primary btn-block" type="submit">Sign Up</button>
            </div>
            <div class="col-md-6">
                <button class="g-signin " 
                    data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email"
                    data-requestvisibleactions="http://schemas.google.com/AddActivity"
                    data-clientId="1049178870057-usbfluijl3qtq3nijmucnsksr9gvkag4.apps.googleusercontent.com"
                    data-accesstype="offline"
                    data-callback="mycoddeSignIn"
                    data-theme="dark"
                    data-cookiepolicy="single_host_origin">
                </button>
            </div>
        </div>
         

      </form>

    </div> <!-- /container -->

Javascript Code for the Google+ API and Fetching User Details, Email from Google Profile

    <script type="text/javascript">
    var gpclass = (function(){
    
    //Defining Class Variables here
    var response = undefined;
    return {
        //Class functions / Objects
        
        mycoddeSignIn:function(response){
            // The user is signed in
            if (response['access_token']) {
            
                //Get User Info from Google Plus API
                gapi.client.load('plus','v1',this.getUserInformation);
                
            } else if (response['error']) {
                // There was an error, which means the user is not signed in.
                //alert('There was an error: ' + authResult['error']);
            }
        },
        
        getUserInformation: function(){
            var request = gapi.client.plus.people.get( {'userId' : 'me'} );
            request.execute( function(profile) {
                var email = profile['emails'].filter(function(v) {
                    return v.type === 'account'; // Filter out the primary email
                })[0].value;
                var fName = profile.displayName;
                $("#inputFullname").val(fName);
                $("#inputEmail").val(email);
            });
        }
    
    }; //End of Return
    })();
    
    function mycoddeSignIn(gpSignInResponse){
        gpclass.mycoddeSignIn(gpSignInResponse);
    }
    </script>


If you click on the Google+ Login Button it will show a popup like below. This means your configuration in google developer console is right.
Login using Google Popup 

Thats it.

30 comments:

  1. Sir I am getting an error "origin mismatch" can u just tell me the solution for it?

    ReplyDelete
    Replies
    1. sir...how can i get image with this

      Delete
    2. use any server or local server to host your file. origin mismatch error will b solve

      Delete
  2. sir, how can i get image with this....

    ReplyDelete
  3. I get the same error: origin mismatch

    ReplyDelete
  4. I get the same error: origin mismatch

    ReplyDelete
  5. i want Google sign-in using Javascript API without triggering popup,it render on same page not in new window.

    ReplyDelete
  6. I used to get origin mismatch error. Now that is gone, but seems when I login for the first time - no message is displayed, again if I hit login button, another login button is replicated below the original button. Plz help.

    ReplyDelete
  7. Is there a way for the contents of the popup to be in browser instead?

    ReplyDelete
  8. Coach Outlet Store Is Your One Stop Shop For Coach, Dooney, Coach Handbags and Coach Purses Cheap.
    Coach Bags

    ReplyDelete
  9. I tried downloading the example and I have replaced it with my client code as well But when I try clicking on the google Sign In button it does not seem to work. It is just idle. Can you please help me out on the same.

    ReplyDelete
  10. I am getting an error "origin mismatch". How to solve it

    ReplyDelete
  11. sir , on page load i dont want to get value from g+ ....how can i do that

    ReplyDelete
  12. Use less, You should give description.. We dont want to copy and paste man please give a description of codes..

    ReplyDelete
    Replies
    1. Code itself is self explanatory.

      If you are Beginner you need to read the linked google API documentation to have clear understanding.

      Delete
  13. if "origin mismatch" popsup replace your client id in the above example.

    ReplyDelete
  14. Hi ,
    Thanku soo much my time got saved . your code is very simple and working exactly how you explained.

    ReplyDelete
  15. Successful Solution to origin mismatch:

    In https://console.developers.google.com
    click on your project

    In Authorized javascript origins:

    If you are working in localhost you must type 3 urls

    For example:

    If the port is 80 then type:

    http://127.0.0.1:80

    and

    http://localhost

    and

    https://localhost

    And it works !!

    ReplyDelete
  16. Error: redirect_uri_mismatch

    Application: Default Demo App

    this is the error i am getting when i click on sign in. can you please help me

    ReplyDelete
  17. how i get get back response after anthentication of google on our page.

    ReplyDelete
  18. Hi Thank You for this article. It helped me a lot. And I want to know after user is authenticated how to get User username and password?

    ReplyDelete
    Replies
    1. You cannot get username password of Google account.

      Only the requested details like email, date of birth, age and all

      Delete
    2. You cannot get username password of Google account.

      Only the requested details like email, date of birth, age and all

      Delete
  19. Successful Solution to origin mismatch:

    In https://console.developers.google.com
    click on your project

    In Authorized javascript origins:

    If you are working in localhost you must type 3 urls

    For example:

    If the port is 80 then type:

    http://127.0.0.1:80

    and

    http://localhost

    and

    https://localhost

    And it works !!

    ReplyDelete
  20. What if we firstly want to see the demo. When we click on the demo button it shows the error 'origin mismatch'. How we can give it the client id?

    ReplyDelete