1

好的,所以我正在尝试使用 Javascript 和 WinJS 为 Windows 8 构建一个小型 Twitter 客户端。我已经获得了请求 oauth 令牌以及 oauth 验证程序。Microsoft 的一个模板是一个很好的资源。不过,我似乎无法在网上找到任何关于 Javascript 和 oAuth 的帮助。无论如何,这是我的代码。我需要弄清楚在这里获取 oAuth 访问令牌表格并存储它们。

////
////    The function of this file is to connect with Twitter via oAuth
////

(function () {
    "use strict";

    //Define a namespace to keep track of controls 
    WinJS.Namespace.define("Account", {
        options: {                                                          // This is the object containing the apps
            consumerKey: ********,                          // Twitter credentials
            consumerSecret: **********,
            callback: *************
        }
    });

    Account.sendRequest = function (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");
        }
    };

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

    Account.getVerifier = function (returned) {
        var URLstring = returned;    //returned;
        var oauth_token;
        Account.oauth_verifier = "";
        URLstring = URLstring.substring("http://novodevelopment.tk/?".length);
        var valuePairs = URLstring.split("&");
        for (var i = 0; i < valuePairs.length; i++) {
            var splits = valuePairs[i].split("=");
            switch (splits[0]) {
                case "oauth_token":
                    oauth_token = splits[1];
                    break;
                case "oauth_verifier":
                    Account.oauth_verifier = splits[1];
                    console.log("oAuth Verifier: " + Account.oauth_verifier);
                    break;
            }
        }
    };

    Account.convertTokens = function (url, authzheader) {
        try {
            var request = new XMLHttpRequest();
            request.open("POST", url, false);
            request.setRequestHeader("Authorization", authzheader);
            request.setRequestHeader("oauth_verifier", Account.oauth_verifier);
            reqest.send(null);
            return request.responseText;
        } catch (err) {
            console.log("failure");
        }

    };

    Account.authzInProcess = false;

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

        // Get all parameters
        var clientID = Account.options.consumerKey;
        var clientSecret = Account.options.consumerSecret;
        var callBackURL = Account.options.callback;

        // Get Date
        var timestamp = Math.round(new Date().getTime() / 1000.0);

        // Create a nonce
        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.
        //    To be fair I found all of this part online
        //    It basically serves the same purpose as jsOAuth
        var sigBaseStringParams = "oauth_callback=" + encodeURIComponent(Account.options.callback);
        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(Account.options.callback) + "\", 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 = Account.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;
            }
        }

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

        var startURI = new Windows.Foundation.Uri(twitterURL);
        var endURI = new Windows.Foundation.Uri(Account.options.callback);

        Account.authzInProgress = true;

        Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
            Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI)
            .done(function (result) {
                console.log("Authenticated URL: " + result.responseData);
                var returnData = result.responseData;
                Account.getVerifier(returnData);
                Account.authzInProgress = false;
            }, function (err) {
                console.log("Error returned by WebAuth broker: " + err, "Web Authentication SDK Sample", "error");
                Account.authzInProgress = false;
            });

        var authzheader = {
            oauth_consumer_key: clientID,
            oauth_nonce: nonce,
            oauth_signature: signature,
            oauth_signature_method: "HMAC-SHA1",
            oauth_timestamp: timestamp,
            oauth_token: oauth_token,
            oauth_version: "1.0"
        };
        var twitterURL = "https://api.twitter.com/oauth/access_token";
   //     var converted = Account.convertTokens(twitterURL);


        Account.convertTokens(twitterURL);

    };



})();

抱歉有点乱

4

2 回答 2

0

我解决了这个问题,但是由于与我的雇主的保密协议,我可能无法共享大部分代码。

看看这个博客:

http://www.wackylabs.net/2011/12/oauth-and-flickr-part-2/

我未能将请求令牌转换为访问令牌,因为我使用的密钥不正确。

我盲目地使用:app_secret + '&' 作为我的关键材料。

当你去升级时,你需要 app_secret + '&' + oauth_token_secret。

这可能没有多大意义,但是如果您想了解更多信息,请给我发消息。

于 2012-08-18T07:09:57.360 回答
0

要存储信息,您可以使用允许您存储本地/漫游设置/文件的Windows.Storage.ApplicationData类。

我建议您使用漫游设置/文件,因为您的应用程序可以通过不同的设备访问,这意味着如果您的应用程序安装在两个设备上,例如台式机和笔记本电脑,您可以从两个设备访问存储的信息。关联是通过 LiveID 完成的。

如果您没有使用 LiveID 登录,或者您没有互联网连接(在目前的情况下,这对于 Twitter 客户端 J 来说会有点问题),则设置/文件将在本地保存。

我希望这会有所帮助。

于 2012-07-02T09:49:32.230 回答