2

如使用 OAuth 2.0 的谷歌开发者页面中所述,我为相应的客户端 ID 创建了唯一 URL

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 解析响应时,它给出的是失败而不是成功。

我在重定向 url 页面中使用了以下 javascript:

<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 工作正常,我能够获取变量的访问令牌,然后我想使用URL https://www.googleapis.com/oauth2/v1/userinfo向谷歌服务器发送 GET 请求jquery ajax,但它会进入错误函数。当我使用 access_token 手动执行 URL 请求时,它给了我一个包含用户所有详细信息的 json 数组。我也尝试将数据类型更改为 jsonp 但没有用。

如果这种方法不可行,任何人都可以建议我如何处理获取用户信息的响应。请也尝试给我一个示例代码。

4

1 回答 1

6

此代码运行良好,我能够获取用户信息,以供参考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>
于 2012-04-30T09:03:37.927 回答