1

在我的 Windows 8 应用程序中尝试使用 Twitter 进行身份验证已经一个多星期了,但没有成功。

我的应用程序已在 Twitter 上注册,它应该能够读取、写入和登录。

我想我已经尝试了 Twitter 文档中的所有描述,但没有任何效果。猜猜问题出在我身上,但找不到。

我总是得到 403 禁止响应。

我的代码:

function getTwitterCredentials() {

    WinJS.xhr({
        type:"get",
        url: "https://api.twitter.com/oauth/authenticate",
        headers: {
            consumerKey: "ZSNRXXXXXXXXX",
            userKey: "GVknHzXXXXXXXXXXXXXXXXXXX",
            Authorization: "OAuth",
            oauth_consumer_key: "ZSNRtXXXXXXXXXXXXX",
            oauth_nonce: "b7efbXXXXXXXXXXXXXXXx",
            oauth_signature: "23zb0XXXXXXXXXXXXXXx",
            oauth_signature_method: "HMAC-SHA1",
            oauth_timestamp: "1368555677",
            oauth_token: "1408XXXXXXXXXXXXXXXXXXXXXXXXXXXXx",
            oauth_version: "1.0"
        }
    }).done(function (response) {
       //it it works here some will be some action 
    }, function error(response) {
        console.log(response.status);
    });
}

有人有这个问题的经验吗?

谢谢马洛

4

1 回答 1

1

这是一些演示 JS 代码,我从我们网站上的 oAuth Web Authentication Broker for Win8 演示中的现有示例稍加修改。在“oob”中搜索我的更改,它们是次要的。

此外,Linq to Twitter 项目非常棒,所以可能要考虑检查一下,这样可能会更容易一些。它相当自动地处理身份验证,并且不需要输入令牌响应。


//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";
    var page = WinJS.UI.Pages.define("/html/oAuthTwitter.html", {
        ready: function (element, options) {
            document.getElementById("oAuthTwitterLaunch").addEventListener("click", launchTwitterWebAuth, false);
            //did read that this is required for oAuth in a win8 app, however twitter uses 'oob' for a desktop app's callback url.
            //in fact your app will show it.
            //var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();
            //document.getElementById("TwitterCallbackURL").innerText = endURI.displayUri;
        }
    });

    function sendRequest(url) {
        try {
            var request = new XMLHttpRequest();
            request.open("GET", url, false);
            request.send(null);
            return request.responseText;
        } catch (err) {
            WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");
        }
    }

    function sendPostRequest(url, authzheader) {
        try {
            var request = new XMLHttpRequest();
            request.open("POST", url, false);
            request.setRequestHeader("Authorization", authzheader);
            request.send(null);
            if (request.status != "200") {
                console.log(request);
            }
            return request.responseText;
        } catch (err) {
            WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");            
        }
    }

    function isValidUriString(uriString) {
        var uri = null;
        try {
            uri = new Windows.Foundation.Uri(uriString);
        }
        catch (err) {
        }
        return uri !== null;
    }

    var authzInProgress = false;

    function launchTwitterWebAuth() {
        var twitterURL = "https://api.twitter.com/oauth/request_token";

        // Get all the parameters from the user
        var clientID = document.getElementById("TwitterClientID").value;
        if (clientID === null || clientID === "") {
            WinJS.log("Please enter a ClientID for Twitter App", "Web Authentication SDK Sample", "error");            
            return;
        }

        var clientSecret = document.getElementById("TwitterSecret").value;
        if (clientSecret === null || clientSecret === "") {
            WinJS.log("Please enter a Secret for Twitter App", "Web Authentication SDK Sample", "error");            
            return;
        }

        var callbackURL = document.getElementById("TwitterCallbackURL").value;
        //if (!isValidUriString(callbackURL)) {
        //    WinJS.log("Please enter a Callback URL for Twitter", "Web Authentication SDK Sample", "error");            
        //    return;
        //}

        if (authzInProgress) {
            document.getElementById("TwitterDebugArea").value += "\r\nAuthorization already in Progress ...";
            return;
        }

        // Acquiring a request token
        var timestamp = Math.round(new Date().getTime() / 1000.0);
        var nonce = Math.random();
        nonce = Math.floor(nonce * 1000000000);

        // Compute base signature string and sign it.
        //    This is a common operation that is required for all requests even after the token is obtained.
        //    Parameters need to be sorted in alphabetical order
        //    Keys and values should be URL Encoded.
        var sigBaseStringParams = "oauth_callback=" + encodeURIComponent(callbackURL);
        sigBaseStringParams += "&" + "oauth_consumer_key=" + clientID;
        sigBaseStringParams += "&" + "oauth_nonce=" + nonce;
        sigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
        sigBaseStringParams += "&" + "oauth_timestamp=" + timestamp;
        sigBaseStringParams += "&" + "oauth_version=1.0";
        var sigBaseString = "POST&";
        sigBaseString += encodeURIComponent(twitterURL) + "&" + encodeURIComponent(sigBaseStringParams);

        var keyText = 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);
        var dataToPost = "OAuth oauth_callback=\"" + encodeURIComponent(callbackURL) + "\", oauth_consumer_key=\"" + clientID + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timestamp + "\", oauth_version=\"1.0\", oauth_signature=\"" + encodeURIComponent(signature) + "\"";
        var response = sendPostRequest(twitterURL, dataToPost);
        var oauth_token;
        var oauth_token_secret;
        var keyValPairs = response.split("&");

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

        document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token = " + oauth_token;
        document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token Secret = " + oauth_token_secret;

        // Send the user to authorization
        twitterURL = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;

        document.getElementById("TwitterDebugArea").value += "\r\nNavigating to: " + twitterURL + "\r\n";
        var startURI = new Windows.Foundation.Uri(twitterURL);
        //var endURI = new Windows.Foundation.Uri(callbackURL);
        //we use 'oob' in the request_auth, but now for authorize, we use the apps URI.
        var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();
        authzInProgress = true;
        Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
            Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI)
            .done(function (result) {
                document.getElementById("TwitterReturnedToken").value = result.responseData;
                document.getElementById("TwitterDebugArea").value += "Status returned by WebAuth broker: " + result.responseStatus + "\r\n";
                if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {
                    document.getElementById("TwitterDebugArea").value += "Error returned: " + result.responseErrorDetail + "\r\n";
                }
                authzInProgress = false;
            }, function (err) {
                WinJS.log("Error returned by WebAuth broker: " + err, "Web Authentication SDK Sample", "error");
                document.getElementById("TwitterDebugArea").value += " Error Message: " + err.message + "\r\n";
                authzInProgress = false;
            });
    }
})();

于 2013-06-03T19:35:40.483 回答