本文介绍了使用 WinJS 的 Twitter OAuth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个多星期以来,我一直试图通过我的 Windows 8 应用程序通过 Twitter 进行身份验证,但没有成功.

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

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

我总是收到 403 禁止响应.

我的代码:

function getTwitterCredentials() {WinJS.xhr({类型:获取",网址:https://api.twitter.com/oauth/authenticate",标题:{消费者密钥:ZSNRXXXXXXXXX",userKey: "GVknHzXXXXXXXXXXXXXXXXXXX",授权:OAuth",oauth_consumer_key: "ZSNRtXXXXXXXXXXXXX",oauth_nonce: "b7efbXXXXXXXXXXXXXXXX",oauth_signature: "23zb0XXXXXXXXXXXXXXXX",oauth_signature_method: "HMAC-SHA1",oauth_timestamp: "1368555677",oauth_token: "1408XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",oauth_version:1.0"}}).完成(功能(响应){//它在这里工作有些将是一些动作}, 函数错误(响应){控制台日志(响应状态);});}

有人遇到过这个问题吗?

谢谢马洛

解决方案

这里有一些演示 JS 代码,我从我们网站上的 oAuth Web Authentication Broker for Win8 演示中的现有示例中稍加修改.在oob"中搜索我的更改,它们很小.

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

////此代码和信息按原样"提供;不保证////任何形式,无论是明示的还是暗示的,包括但不限于////适销性和/或适用性的默示保证////特殊用途.////////版权所有 (c) 微软公司.版权所有(功能 () {严格使用";var page = WinJS.UI.Pages.define("/html/oAuthTwitter.html", {准备好:功能(元素,选项){document.getElementById("oAuthTwitterLaunch").addEventListener("click", launchTwitterWebAuth, false);//确实读到这是在 win8 应用程序中 oAuth 所必需的,但是 twitter 使用oob"作为桌面应用程序的回调 url.//事实上你的应用程序会显示它.//var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();//document.getElementById("TwitterCallbackURL").innerText = endURI.displayUri;}});函数发送请求(网址){尝试 {var request = new XMLHttpRequest();request.open(GET", url, false);request.send(null);返回 request.responseText;} 抓住(错误){WinJS.log("发送请求时出错:"+ err,"Web Authentication SDK Sample", "error");}}函数 sendPostRequest(url, authzheader) {尝试 {var request = new XMLHttpRequest();request.open(POST", url, false);request.setRequestHeader(授权", authzheader);request.send(null);如果(请求状态!=200"){控制台日志(请求);}返回 request.responseText;} 抓住(错误){WinJS.log("发送请求时出错:"+ err,"Web Authentication SDK Sample", "error");}}函数 isValidUriString(uriString) {var uri = null;尝试 {uri = new Windows.Foundation.Uri(uriString);}抓住(错误){}返回 uri !== null;}var authzInProgress = false;功能启动TwitterWebAuth(){var twitterURL = "https://api.twitter.com/oauth/request_token";//获取用户的所有参数var clientID = document.getElementById("TwitterClientID").value;if (clientID === null || clientID === "") {WinJS.log(请输入 Twitter 应用程序的 ClientID"、Web 身份验证 SDK 示例"、错误");返回;}var clientSecret = document.getElementById("TwitterSecret").value;if (clientSecret === null || clientSecret === "") {WinJS.log(请输入 Twitter 应用程序的密码"、Web 身份验证 SDK 示例"、错误");返回;}var callbackURL = document.getElementById("TwitterCallbackURL").value;//if (!isValidUriString(callbackURL)) {//WinJS.log(请输入 Twitter 的回调 URL"、Web 身份验证 SDK 示例"、错误");// 返回;//}如果(authzInProgress){document.getElementById("TwitterDebugArea").value += "\r\n授权已经在进行中......";返回;}//获取请求令牌var 时间戳 = Math.round(new Date().getTime()/1000.0);var nonce = Math.random();nonce = Math.floor(nonce * 1000000000);//计算基本签名字符串并对其进行签名.//这是一个常见的操作,即使在获取到令牌后,所有请求也需要执行此操作.//参数需要按字母顺序排序//键和值应该是 URL 编码的.var sigBaseStringParams = "oauth_callback="+ encodeURIComponent(callbackURL);sigBaseStringParams += "&";+ oauth_consumer_key="+ 客户 ID;sigBaseStringParams += "&";+oauth_nonce="+ 随机数;sigBaseStringParams += "&";+oauth_signature_method=HMAC-SHA1";sigBaseStringParams += "&";+oauth_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 签名 = 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=\"";+ 时间戳 +\",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("=");开关(拆分[0]){案例oauth_token":oauth_token = 拆分 [1];休息;案例oauth_token_secret":oauth_token_secret = splits[1];休息;}}document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token = ";+ oauth_token;document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token Secret = ";+ oauth_token_secret;//向用户发送授权twitterURL = "https://api.twitter.com/oauth/authorize?oauth_token="+ oauth_token;document.getElementById("TwitterDebugArea").value += "\r\n导航到:"+ twitterURL + "\r\n";var startURI = new Windows.Foundation.Uri(twitterURL);//var endURI = new Windows.Foundation.Uri(callbackURL);//我们在 request_auth 中使用 'oob',但现在为了授权,我们使用了应用程序 URI.var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();authzInProgress = 真;Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(Windows.Security.Authentication.Web.WebAuthenticationOptions.none、startURI、endURI).done(功能(结果){document.getElementById("TwitterReturnedToken").value = result.responseData;document.getElementById("TwitterDebugArea").value +="WebAuth 代理返回的状态:"+ result.responseStatus + "\r\n";if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {document.getElementById("TwitterDebugArea").value +="错误返回:"+ result.responseErrorDetail + "\r\n";}authzInProgress = 假;}, 函数(错误){WinJS.log("WebAuth 代理返回的错误:"+ err,"Web Authentication SDK Sample", "error");document.getElementById("TwitterDebugArea").value += ";错误信息:"+ err.message + "\r\n";authzInProgress = 假;});}})();

Trying to authenticate with Twitter since over a week trough my Windows 8 app, but no success.

My app is registered at Twitter and it should be able to read, write and sign in.

I think I've tried all the descriptions at Twitter documentation, but nothing works. Guess the problem is at me, but can't find it.

I get always the 403 forbidden response.

My code:

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

Someone has experience whit this issue?

Thanks Marlowe

解决方案

Here's some demo JS code I slightly modified from an existing sample on our site from the oAuth Web Authentication Broker for Win8 demo. Search 'oob' for my changes, they are minor.

In addition, the Linq to Twitter project is pretty awesome so may want to consider checking that out as well and would prob be a bit easier. It handles the auth fairly automatically and doesn't require having to enter in the token response.


//// 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;
            });
    }
})();

这篇关于使用 WinJS 的 Twitter OAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:26