如何在Windows 8 JavaScript(Metro)中将twitter oAuth请求令牌转换为访问令牌

时间:2012-06-27 18:44:19

标签: javascript oauth windows-8 microsoft-metro twitter-oauth

好的,我正在尝试使用Javascript和WinJS为Windows 8构建一个小型的Twitter客户端。 我已经获得了oauth令牌以及oauth验证器的请求。微软的一个模板是一个很好的资源。我似乎无法在线找到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);

    };



})();

抱歉它有点混乱

2 个答案:

答案 0 :(得分:0)

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

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

如果您没有使用LiveID登录,或者您没有互联网连接(在本案例中对于Twitter客户端J来说有点问题),设置/文件将在本地保留。

我希望这有帮助。

答案 1 :(得分:0)

我解决了这个问题,但由于我与雇主的NDA,我可能无法分享大部分代码。

看一下这个博客:

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

我无法将请求令牌转换为访问令牌,因为我使用的秘密不正确。

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

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

这可能没什么意义,但如果你想要更多信息必须给我留言。