2

我正在为 windows phone 7 构建一个 twitter 应用程序。但是 twitter 的 OAuth 给我带来了很多问题。我正在尝试获取请求令牌,并且每次收到消息:无法验证 oauth 签名和令牌。任何帮助,将不胜感激。

这是我的代码:

参数基本字符串:

public static string GetParameterString()
    {
        SystemParameters SysParameters = new SystemParameters();
        Parameters Param = new Parameters();
        StringBuilder sb = new StringBuilder();
        sb.Append(SysParameters.CallbackUrl()).Append("=");
        sb.Append(PercentEncoder(Param.callbackURL)).Append("&");
        sb.Append(SysParameters.CosumerToken()).Append("=");
        sb.Append(PercentEncoder(Param.consumerKey)).Append("&");
        sb.Append(SysParameters.Nonce()).Append("=");
        sb.Append(PercentEncoder(GetNonce())).Append("&");
        sb.Append(SysParameters.SignatureMethod()).Append("=");
        sb.Append(PercentEncoder("HMAC-SHA1")).Append("&");
        sb.Append(SysParameters.TimeStamp()).Append("=");
        sb.Append(PercentEncoder(GetTimeStamp().ToString())).Append("&");
        sb.Append(SysParameters.OauthVersion()).Append("=");
        sb.Append(PercentEncoder("1.0"));

        return sb.ToString();
    }

签名基本字符串:

public static string GetSignatureBase()
    {
        SystemParameters SysParameters = new SystemParameters();
        Parameters Param = new Parameters();
        StringBuilder sb = new StringBuilder();

        sb.Append("POST").Append("&");
        sb.Append(PercentEncoder(SysParameters.RequestTokenURL())).Append("&");
        sb.Append(PercentEncoder(GetParameterString()));

        return sb.ToString();
    }

获取签名:

public static string GetSignature()
{
   SystemParameters SysParameters = new SystemParameters();
   Parameters param = new Parameters();

   string signature;

   signature = Convert.ToBase64String((new HMACSHA1(Encoding.UTF8
                       .GetBytes(PercentEncoder(param.consumerSecret) + "&")))
                       .ComputeHash(Encoding.UTF8.GetBytes(GetSignatureBase())));

   return PercentEncoder(signature);      
 }

获取令牌:

private void button2_Click(object sender, RoutedEventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        sb.Append(param.RequestURL)
                        .Append(OauthHelper.RequestType.RequesToken).Append("?");
        sb.Append(sysParam.CallbackUrl()).Append("=");
        sb.Append(OauthHelper.PercentEncoder(param.callbackURL)).Append("&");
        sb.Append(sysParam.CosumerToken()).Append("=");
        sb.Append(OauthHelper.PercentEncoder(param.consumerKey)).Append("&");
        sb.Append(sysParam.Nonce()).Append("=");
        sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetNonce())).Append("&");
        sb.Append(sysParam.Signature()).Append("=");
        sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetSignature())).Append("&");
        sb.Append(sysParam.SignatureMethod()).Append("=");
        sb.Append(OauthHelper.PercentEncoder("HMAC-SHA1")).Append("&");
        sb.Append(sysParam.TimeStamp()).Append("=");
        sb.Append(OauthHelper.PercentEncoder(OauthHelper.GetTimeStamp().ToString()))
                                                                        .Append("&");
        sb.Append(sysParam.OauthVersion()).Append("=");
        sb.Append(OauthHelper.PercentEncoder("1.0"));

        WebBrowserTask task = new WebBrowserTask();
        task.URL = sb.ToString();

        task.Show();

    }
4

1 回答 1

0

我已经完成了这个实现,引用了另一个代码..我的代码是这样的..

#region web query response methods
    /// <summary>
    /// Event that initiates QueryResponse for RequestToken request
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e">Webresponse event argument</param>
    void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
    {
        try
        {
            var parameters = TwitterHelperMethods.GetQueryParameters(e.Response);
            OAuthTokenKey = parameters["oauth_token"];
            tokenSecret = parameters["oauth_token_secret"];
            var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;

            Dispatcher.BeginInvoke(() =>
            {
                this.browseTwitter.Navigate(new Uri(authorizeUrl));
            });
        }
        catch (Exception ex)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(ex.Message);
            });
        }
    }

    /// <summary>
    /// Event that initiates QueryResponse for AccessToken request
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e">Webresponse event argument</param>
    void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
    {
        try
        {
            var parameters = TwitterHelperMethods.GetQueryParameters(e.Response);
            accessToken = parameters["oauth_token"];
            accessTokenSecret = parameters["oauth_token_secret"];
            userID = parameters["user_id"];
            userScreenName = parameters["screen_name"];

            TwitterHelperMethods.SetKeyValue<string>("AccessToken", accessToken);
            TwitterHelperMethods.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
            TwitterHelperMethods.SetKeyValue<string>("ScreenName", userScreenName);

            cacheManager.SaveToIsolatedStorage(Utilities.TwitterID, userID);
            cacheManager.SaveToIsolatedStorage(Utilities.TwitterAccessToken, accessToken);
            cacheManager.SaveToIsolatedStorage(Utilities.TwitterSecretAccessToken, accessTokenSecret);
            // NavigationService.Navigate(new Uri("/HomePage.xaml", UriKind.RelativeOrAbsolute));
        }
        catch (Exception ex)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(ex.Message);
            });
        }
    }
    #endregion

    #region Browser events methods

    /// <summary>
    /// Called after the broswer is loaded
    /// </summary>
    /// <param name="sender">Browser</param>
    /// <param name="e">Routed Event arguments</param>
    private void browseTwitter_Loaded(object sender, RoutedEventArgs e)
    {
        accessToken = TwitterHelperMethods.GetKeyValue<string>("AccessToken");
        accessTokenSecret = TwitterHelperMethods.GetKeyValue<string>("AccessTokenSecret");
        userScreenName = TwitterHelperMethods.GetKeyValue<string>("ScreenName");

        if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
        {
            var requestTokenQuery = TwitterOAuthHelper.GetRequestTokenQuery();
            requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
            requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
        }
    }

    /// <summary>
    /// Called when browser Initiates Navigation to Uri provided
    /// </summary>
    /// <param name="sender">Browser</param>
    /// <param name="e">Navigating event arguments</param>
    private void browseTwitter_Navigating(object sender, NavigatingEventArgs e)
    {
        if (e.Uri.ToString().StartsWith(TwitterSettings.CallbackUri))
        {
            cacheManager = new CacheManager();
            var AuthorizeResult = TwitterHelperMethods.GetQueryParameters(e.Uri.ToString());
            var VerifyPin = AuthorizeResult["oauth_verifier"];

            //We now have the Verification pin
            //Using the request token and verification pin to request for Access tokens

            var AccessTokenQuery = TwitterOAuthHelper.GetAccessTokenQuery(
                                                                     OAuthTokenKey,     //The request Token
                                                                     tokenSecret,       //The request Token Secret
                                                                     VerifyPin         // Verification Pin
                                                                    );
            AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
            AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
            NavigationService.Navigate(new Uri("/OtherPages/HomePage.xaml", UriKind.RelativeOrAbsolute));
        }
    }
    #endregion

我的 Twitterhelpermethods 类是这样的

public class TwitterHelperMethods
{
    public static Dictionary<string, string> GetQueryParameters(string response)
    {
        Dictionary<string, string> nameValueCollection = new Dictionary<string, string>();
        string[] items = response.Split('&');

        foreach (string item in items)
        {
            if (item.Contains("="))
            {
                string[] nameValue = item.Split('=');
                if (nameValue[0].Contains("?"))
                    nameValue[0] = nameValue[0].Replace("?", "");
                nameValueCollection.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
            }
        }
        return nameValueCollection;
    }
}

和 twitteroauthhelper.cs 是

public class TwitterOAuthHelper
{
    public static OAuthWebQuery GetRequestTokenQuery()
    {
        var oauth = new OAuthWorkflow
        {
            ConsumerKey = TwitterSettings.consumerKey,
            ConsumerSecret = TwitterSettings.consumerKeySecret,
            SignatureMethod = OAuthSignatureMethod.HmacSha1,
            ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
            RequestTokenUrl = TwitterSettings.RequestTokenUri,
            Version = TwitterSettings.oAuthVersion,
            CallbackUrl = TwitterSettings.CallbackUri
        };

        var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
        var objOAuthWebQuery = new OAuthWebQuery(info);
        objOAuthWebQuery.HasElevatedPermissions = true;
        objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
        objOAuthWebQuery.SilverlightMethodHeader = "GET";
        return objOAuthWebQuery;
    }

    public static OAuthWebQuery GetAccessTokenQuery(string requestToken, string RequestTokenSecret, string oAuthVerificationPin)
    {
        var oauth = new OAuthWorkflow
        {
            AccessTokenUrl = TwitterSettings.AccessTokenUri,
            ConsumerKey = TwitterSettings.consumerKey,
            ConsumerSecret = TwitterSettings.consumerKeySecret,
            ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
            SignatureMethod = OAuthSignatureMethod.HmacSha1,
            Token = requestToken,
            Verifier = oAuthVerificationPin,
            Version = TwitterSettings.oAuthVersion
        };

        var info = oauth.BuildAccessTokenInfo(WebMethod.Post);
        var objOAuthWebQuery = new OAuthWebQuery(info);
        objOAuthWebQuery.HasElevatedPermissions = true;
        objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
        objOAuthWebQuery.SilverlightMethodHeader = "GET";
        return objOAuthWebQuery;
    }
}

twittersettings.cs :-

public class TwitterSettings
{
    public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
    public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
    public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";

    public static string CallbackUri = "http://www.qwinixtech.com";

    public static string StatusUpdateUrl { get { return "http://api.twitter.com"; } }

    // #error TODO REGISTER YOUR APP WITH TWITTER TO GET YOUR KEYS AND FILL THEM IN HERE
    public static string consumerKey = "Your consumer key here";
    public static string consumerKeySecret = "Your consumer secret key here";

    public static string AccessToken = "Your access token here";
    public static string AccessTokenSecret = "Your Secret access token here";

    public static string oAuthVersion = "1.0a";

}

这工作得很好..你需要做的只是吊床库..我希望你已经拥有它..否则请下载它..

于 2012-10-26T06:10:12.553 回答