tinku
tinku

Reputation: 479

Unable to get user info after successfully logging with google OAuth 2.0

As described in the google's developers page using OAuth 2.0, I created the unique URL for the appropriate client id

format of the URL is :

https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
state=%2Fprofile&
redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Foauthcallback&
response_type=token&
client_id=812741506391.apps.googleusercontent.com

Users are able to login and are redirected to my redirect URL but the problem is, when I try to use jquery to parse the response its giving a failure rather that of a Success.

I'm using the following javascript in my redirect url page:

<script>
// First, parse the query string
var acc_token;
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
    if(m[1]=="access_token")
    acc_token = m[2];
  params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}

// And send the token over to the server
var req = new XMLHttpRequest();
// consider using POST so query isn't logged
req.open('GET', 'https://' + window.location.host + '/catchtoken?' + queryString, true);

req.onreadystatechange = function (e) {
  if (req.readyState == 4) {
     if(req.status == 200){
       window.location = params['state']
   }
  else if(req.status == 400) {
      //  alert('There was an error processing the token.')
    }
    else {
     // alert('something else other than 200 was returned')
    }
  }
};
req.send(null);

  $.ajax({
        type: 'GET',
       url:"https://www.googleapis.com/oauth2/v1/userinfo?access_token="+acc_token,
       datatype : "json",
       success : function(data)
    {
        console.log(data);
    },
    error : function()
    {
        alert("Failure!");
    }

    });
</script>

The javascript is working fine, I'm able to get the access token to a variable and then i want to send a GET request to the google server for the URL https://www.googleapis.com/oauth2/v1/userinfo using the jquery ajax, but its going to the error function. when I manually do the URL with access_token request its giving me a json array with all the details of the user. I also tried changing the datatype to jsonp but no use.

if this method is not possible can anyone suggest me how to handle the response for getting userinfo. Please, also try to give me a sample code.

Upvotes: 2

Views: 5735

Answers (1)

tinku
tinku

Reputation: 479

This code is working perfectly, I'm able to get user info, for reference goto and here is the working code

 <script src="jquery.js"></script>
    <script>
        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';
        var CLIENTID    =   '716569014051.apps.googleusercontent.com';
        var REDIRECT    =   'http://localhost:8888/MAMP/html5/oauth'
        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;

        function login() {
            var win         =   window.open(_url, "windowname1", 'width=800, height=600'); 

            var pollTimer   =   window.setInterval(function() { 
                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();

                    validateToken(acToken);
                }
            }, 100);
        }

        function validateToken(token) {
            $.ajax({
                url: VALIDURL + token,
                data: null,
                success: function(responseText){  
                    getUserInfo();
                },  
                dataType: "jsonp"  
            });
        }

        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').append(user.name);
                    $('#imgHolder').attr('src', user.picture);
                },
                dataType: "jsonp"
            });
        }

        //credits: http://www.netlobo.com/url_query_string_javascript.html
        function gup(url, name) {
            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var regexS = "[\\#&]"+name+"=([^&#]*)";
            var regex = new RegExp( regexS );
            var results = regex.exec( url );
            if( results == null )
                return "";
            else
                return results[1];
        }

        </script>

<body>
    <a href='#' onClick='login();'> click here to login </a>
    <div id='uName'>Welcome  </div>
    <img src='' id='imgHolder'/>
</body>

Upvotes: 6

Related Questions