无效的凭据错误-google userinfo api

时间:2012-07-20 07:08:56

标签: oauth

我正在尝试通过Google UserInfo API“https://sites.google.com/site/oauthgoog/Home/emaildisplayscope”获取用户的电子邮件地址

我使用的是有效的访问令牌,但仍然收到无效的crdetial错误。 我的应用程序正在实现Oauth 1.0 API是否可能需要Oauth 2令牌。 如果是,获取用户电子邮件地址的另一种方法是什么?

这是我的代码 -

     $('#GMAIL_BUTTON').click(function () {
    //oauth1 approach similar to twitter
    var requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
    var authorizeUrl = "https://www.google.com/accounts/OAuthAuthorizeToken";
    var accessUrl = "https://www.google.com/accounts/OAuthGetAccessToken";
    var callbackUrl = "http://abcd.com/dfdf.php";
    var scope = "https://mail.google.com/ https://www.googleapis.com/auth/userinfo.email      https://www.googleapis.com/auth/userinfo.profile";
    var clientID = "vfdvfdvfd";
    var clientSecret = "dvdfvrevvfv-fvfdvf";
    var timestamp = Math.round(new Date().getTime() / 1000.0);
    var nonce = (new Date()).getTime();   
    var params = [];
    params["oauth_callback"] = encodeURI(callbackUrl);
    params["oauth_consumer_key"] = clientID;
    params["oauth_timestamp"] = timestamp;
    params["oauth_nonce"] = nonce;
    params["oauth_signature_method"] = "HMAC-SHA1";
    params["scope"] = scope;
    var paramString = normalizeParams(params);
    var sigBaseString = "GET&" + encodeURIComponent(requestUrl) + "&" + encodeURIComponent(paramString);
    var keyText = encodeURIComponent(clientSecret) + "&";
    var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(keyText, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
    var macAlgorithmProvider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.openAlgorithm("HMAC_SHA1");
    var key = macAlgorithmProvider.createKey(keyMaterial);
    var tbs = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(sigBaseString, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
    var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.sign(key, tbs);
    var signature = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(signatureBuffer);
    paramString += "&oauth_signature=" + encodeURIComponent(signature);
    requestUrl = encodeURI(requestUrl);
    requestUrl += "?" + paramString;
    var response = sendGetRequest(requestUrl);
    //requestUrl += "?scope="+encodeURIComponent(scope);
    //var response = sendGetRequest(requestUrl, dataToPost, null);
    var keyValPairs = response.split("&");
    var oauth_token;
    var oauth_token_secret;
    for (var i = 0; i < keyValPairs.length; i++) {
        var splits = keyValPairs[i].split("=");
        switch (splits[0]) {
            case "oauth_token":
                oauth_token = splits[1];
                break;
            case "oauth_token_secret":
                oauth_token_secret = splits[1];
                break;
        }
    }

    // Send the user to authorization
    authorizeUrl += "?oauth_token=" + oauth_token;

    // document.getElementById("TwitterDebugArea").value += "\r\nNavigating to: " + twitterURL + "\r\n";
    var startURI = new Windows.Foundation.Uri(authorizeUrl);
    var endURI = new Windows.Foundation.Uri(callbackUrl);

    //authzInProgress = true;
    Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
        Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI)
        .done(function (result) {
            var value = result.responseData;
            var callbackPrefix = callbackUrl + "?";
            var dataPart = value.substring(callbackPrefix.length);
            var keyValPairs = dataPart.split("&");
            var authorize_token;
            var oauth_verifier;
            for (var i = 0; i < keyValPairs.length; i++) {
                var splits = keyValPairs[i].split("=");
                switch (splits[0]) {
                    case "oauth_token":
                        authorize_token = splits[1];
                        break;
                    case "oauth_verifier":
                        oauth_verifier = splits[1];
                        break;
                }
            }
           if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {
                //document.getElementById("FacebookDebugArea").value += "Error returned: " + result.responseErrorDetail + "\r\n";
            }
            //form the header and send the verifier in the request to accesstokenurl
           var params = [];
           var timestamp = Math.round(new Date().getTime() / 1000.0);
           var nonce = (new Date()).getTime();
           params["oauth_consumer_key"] = clientID;
           params["oauth_nonce"] = nonce;
           params["oauth_signature_method"] = "HMAC-SHA1";
           params["oauth_timestamp"] = timestamp;
           params["oauth_token"] = authorize_token;
           params["oauth_verifier"] = oauth_verifier;              
           var paramString = normalizeParams(params);

           var sigBaseString = "GET&" + rfcEncoding(accessUrl) + "&" + rfcEncoding(paramString);
           var keyText = rfcEncoding(clientSecret) + "&" + rfcEncoding(oauth_token_secret);
           var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(keyText, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
           var macAlgorithmProvider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.openAlgorithm("HMAC_SHA1");
           var key = macAlgorithmProvider.createKey(keyMaterial);
           var tbs = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(sigBaseString, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
           var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.sign(key, tbs);
           var signature = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(signatureBuffer);
           paramString += "&oauth_signature=" + rfcEncoding(signature);
           accessUrl = encodeURI(accessUrl);
           accessUrl += "?" + paramString;
           var response = sendGetRequest(accessUrl);

            var tokenstartpos = response.indexOf("oauth_token") + 12;
            var tokenendpos = response.indexOf("&oauth_token_secret");
            var secretstartpos = tokenendpos + 20;
            var token = response.substring(tokenstartpos, tokenendpos);
            var secret = response.substring(secretstartpos);


            var gmailinfourl = "https://www.googleapis.com/userinfo/email?access_token="+token;

            WinJS.xhr({url: gmailinfourl}).done(function success(result) {
                var gmail_id = JSON.parse(result.responseText).email_address;

                    //send data to server
                    //more code

            });
           /*

            */
        }, function (err) {
            WinJS.log("Error returned by WebAuth broker: " + err, "Web Authentication SDK Sample", "error");
        });
});    

1 个答案:

答案 0 :(得分:1)

正确userinfo email scope就是这样:

https://www.googleapis.com/auth/userinfo.email

Google弃用了OAuth 1 access,我们鼓励您升级到OAuth 2(这样更简单!),尽管它应该仍然可以使用一段时间。 但是,如果您在弃用后注册了新的client id,则可能只适用于OAuth 2.

<强>更新

您遇到的问题是,您尝试以OAuth 2的方式请求资源:

GET /userinfo/email?access_token=...

OAuth 1的工作方式不同,您可以在Google's OAuth 1 Playground上看到:

GET /userinfo/email?oauth_consumer_key={CONSUMER_KEY}
                   &oauth_nonce={NONCE}
                   &oauth_signature={SIGNATURE}
                   &oauth_signature_method={SIGNATURE_METHOD}
                   &oauth_timestamp={TIMESTAMP}
                   &oauth_token={YOUR_TOKEN}
                   &oauth_version=1.0

更好的是,将OAuth签名包含在请求标头中:

GET /userinfo/email
[...]
Authorization: OAuth oauth_consumer_key="{CONSUMER_KEY}",
                     oauth_nonce="{NONCE}",
                     oauth_signature="{SIGNATURE}",
                     oauth_signature_method="{SIGNATURE_METHOD}",
                     oauth_timestamp="{TIMESTAMP}",
                     oauth_token="{YOUR_TOKEN}",
                     oauth_version="1.0"

有关如何设置的信息,请参阅header参数。