2012-04-26 94 views
2

如使用OAuth 2.0 google's developers page描述登錄成功獲取用戶信息,我創建了獨特的URL爲合適的客戶端ID無法經過與谷歌的OAuth 2.0

URL的格式爲:

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 

用戶能夠登錄並重定向到我的重定向URL,但問題是,當我嘗試使用jquery解析響應時,它給出了失敗,而不是成功。

我用下面的JavaScript在我的重定向URL頁面:

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

JavaScript的工作很好,我能夠獲得訪問令牌給一個變量,然後我想發出一個GET請求使用jquery ajax的URL https://www.googleapis.com/oauth2/v1/userinfo到谷歌服務器,但它的錯誤功能。當我手動做access_token的URL請求時,給我一個包含用戶所有細節的json數組。我也嘗試將數據類型更改爲jsonp,但沒有用。

如果這種方法是不可能的任何人都可以建議我如何處理獲取userinfo的響應。請同時嘗試給我一個示例代碼。

+0

我認爲涉及到跨域它的東西,序解決跨域問題,我們將使用jsonp。我試過但沒有使用 – tinku 2012-04-26 08:02:45

回答

5

該代碼可以正常使用,我能夠獲得用戶信息,以供參考goto這裏是工作的代碼

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

這不適用於IE9 64位 – Amitabh 2012-12-22 11:05:35

+0

記住你需要廣告最新的jquery它說 2015-08-26 19:25:35