public static void WebRequestBuilderParts() { WebRequestBuilder builder = new WebRequestBuilder(new Uri("http://example.com/endpoint"), HTTPVerb.GET) { Tokens = new OAuthTokens() { ConsumerSecret = "518F1B7B4C2F855EFF3DEFDAF1311", AccessTokenSecret = "A6FE4462BAA8C3ADEA7D9E3BCD5BB" } }; // Manually add our values builder.Parameters.Add("oauth_version", "1.0"); builder.Parameters.Add("oauth_nonce", "5565373"); builder.Parameters.Add("oauth_timestamp", "1283303184"); builder.Parameters.Add("oauth_signature_method", "HMAC-SHA1"); builder.Parameters.Add("oauth_consumer_key", "49A8746B34B83CA13D1B9DACFD251"); builder.Parameters.Add("oauth_consumer_secret", "518F1B7B4C2F855EFF3DEFDAF1311"); builder.Parameters.Add("oauth_token", "8B163EC93574682CFF3FD6B45BD55"); builder.Parameters.Add("oauth_token_secret", "A6FE4462BAA8C3ADEA7D9E3BCD5BB"); string signature = builder.GenerateSignature(); Assert.AreEqual(signature, "ndQStX289rIMyZR5dErSinLK/bQ="); builder.Parameters.Add("text", "this is a test http://example.com/test?key=value&key%202"); signature = builder.GenerateSignature(); Assert.AreEqual(signature, "MUUsZ/iV/FXxBRPdyxRkNKqEShw="); builder.Verb = HTTPVerb.POST; signature = builder.GenerateSignature(); Assert.AreEqual(signature, "wtbXMN5BwtH8r2/G/Rwqdp7HMnU="); }
/// <summary> /// Gets a new OAuth request token from the twitter api. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <param name="proxy">The proxy.</param> /// <returns> /// A new <see cref="Twitterizer.OAuthTokenResponse"/> instance. /// </returns> public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress, WebProxy proxy) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/request_token"), HTTPVerb.POST, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }) { Proxy = proxy }; if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) { responseBody = new StreamReader(responseStream).ReadToEnd(); } } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } Match matchedValues = Regex.Match(responseBody, @"oauth_token=(?<token>[^&]+)|oauth_token_secret=(?<secret>[^&]+)|oauth_verifier=(?<verifier>[^&]+)"); return(new OAuthTokenResponse { Token = matchedValues.Groups["token"].Value, TokenSecret = matchedValues.Groups["secret"].Value, VerificationString = matchedValues.Groups["verifier"].Value }); }
/// <summary> /// Gets the request token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <returns></returns> public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } var builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/request_token"), HTTPVerb.POST, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { using (var webResponse = builder.ExecuteRequest()) using (var responseStream = webResponse.GetResponseStream()) { if (responseStream != null) { using (var streamReader = new StreamReader(responseStream)) { responseBody = streamReader.ReadToEnd(); } } } } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return(new OAuthTokenResponse { Token = ParseQuerystringParameter("oauth_token", responseBody), TokenSecret = ParseQuerystringParameter("oauth_token_secret", responseBody), VerificationString = ParseQuerystringParameter("oauth_verifier", responseBody) }); }
/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static async Task <OAuthTokenResponse> AccessTokensAsync(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OAuthTokenResponse response = new OAuthTokenResponse(); try { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Post, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); HttpResponseMessage httpresponse = await builder.ExecuteRequestAsync(); string responseBody = await httpresponse.Content.ReadAsStringAsync(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (responseBody.Contains("user_id=")) { response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); } response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return(response); }
/// <summary> /// Gets the request token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <returns></returns> public static async Task <OAuthTokenResponse> RequestTokenAsync(string consumerKey, string consumerSecret, string callbackAddress) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/request_token"), HttpMethod.Post, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpResponseMessage webResponse = await builder.ExecuteRequestAsync(); Stream responseStream = await webResponse.Content.ReadAsStreamAsync(); if (responseStream != null) { responseBody = new StreamReader(responseStream).ReadToEnd(); } } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return(new OAuthTokenResponse { Token = ParseQuerystringParameter("oauth_token", responseBody), TokenSecret = ParseQuerystringParameter("oauth_token_secret", responseBody), VerificationString = ParseQuerystringParameter("oauth_verifier", responseBody) }); }
/// <summary> /// Gets the access token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="requestToken">The request token.</param> /// <param name="verifier">The pin number or verifier string.</param> /// <param name="proxy">The proxy.</param> /// <returns> /// An <see cref="OAuthTokenResponse"/> class containing access token information. /// </returns> public static OAuthTokenResponse GetAccessToken(string consumerKey, string consumerSecret, string requestToken, string verifier, WebProxy proxy) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HTTPVerb.GET, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Proxy = proxy; if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpWebResponse webResponse = builder.ExecuteRequest(); responseBody = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; return(response); }
/// <summary> /// Adds the OAuth Echo header to the supplied web request. /// </summary> /// <param name="request">The request.</param> /// <param name="tokens">The tokens.</param> public static void AddOAuthEchoHeader(WebRequest request, OAuthTokens tokens) { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/1/account/verify_credentials.json"), HTTPVerb.POST, tokens); builder.PrepareRequest(); request.Headers.Add("X-Verify-Credentials-Authorization", builder.GenerateAuthorizationHeader()); request.Headers.Add("X-Auth-Service-Provider", "https://api.twitter.com/1/account/verify_credentials.json"); }
/// <summary> /// Gets the access token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="requestToken">The request token.</param> /// <param name="verifier">The pin number or verifier string.</param> /// <returns> /// An <see cref="OAuthTokenResponse"/> class containing access token information. /// </returns> public static async Task <OAuthTokenResponse> AccessTokenAsync(string consumerKey, string consumerSecret, string requestToken, string verifier) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Get, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpResponseMessage webResponse = await builder.ExecuteRequestAsync(); responseBody = await webResponse.Content.ReadAsStringAsync(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; return(response); }
/// <summary> /// Adds the OAuth Echo header to the supplied web request. /// </summary> /// <param name="request">The request.</param> /// <param name="tokens">The tokens.</param> public static HttpRequestMessage AddOAuthEchoHeader(HttpRequestMessage request, OAuthTokens tokens) { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/1/account/verify_credentials.json"), HttpMethod.Post, tokens); builder.PrepareRequest(); request.Headers.Add("X-Verify-Credentials-Authorization", builder.GenerateAuthorizationHeader()); request.Headers.Add("X-Auth-Service-Provider", "https://api.twitter.com/1/account/verify_credentials.json"); return(request); }
/// <summary> /// Gets the access token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="requestToken">The request token.</param> /// <param name="verifier">The pin number or verifier string.</param> /// <returns> /// An <see cref="OAuthTokenResponse"/> class containing access token information. /// </returns> public static async Task<OAuthTokenResponse> AccessTokenAsync(string consumerKey, string consumerSecret, string requestToken, string verifier) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Get, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpResponseMessage webResponse = await builder.ExecuteRequestAsync(); responseBody = await webResponse.Content.ReadAsStringAsync(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; return response; }
/// <summary> /// Gets the request token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <returns></returns> public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/request_token"), HTTPVerb.POST, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) responseBody = new StreamReader(responseStream).ReadToEnd(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return new OAuthTokenResponse { Token = ParseQuerystringParameter("oauth_token", responseBody), TokenSecret = ParseQuerystringParameter("oauth_token_secret", responseBody), VerificationString = ParseQuerystringParameter("oauth_verifier", responseBody) }; }
/// <summary> /// Gets a new OAuth request token from the twitter api. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="callbackAddress">The callback address. For PIN-based authentication "oob" should be supplied.</param> /// <param name="proxy">The proxy.</param> /// <returns> /// A new <see cref="Twitterizer.OAuthTokenResponse"/> instance. /// </returns> public static OAuthTokenResponse GetRequestToken(string consumerKey, string consumerSecret, string callbackAddress, WebProxy proxy) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(callbackAddress)) { throw new ArgumentNullException("callbackAddress", @"You must always provide a callback url when obtaining a request token. For PIN-based authentication, use ""oob"" as the callback url."); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/request_token"), HTTPVerb.POST, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }) { Proxy = proxy }; if (!string.IsNullOrEmpty(callbackAddress)) { builder.Parameters.Add("oauth_callback", callbackAddress); } string responseBody = null; try { HttpWebResponse webResponse = builder.ExecuteRequest(); Stream responseStream = webResponse.GetResponseStream(); if (responseStream != null) responseBody = new StreamReader(responseStream).ReadToEnd(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } Match matchedValues = Regex.Match(responseBody, @"oauth_token=(?<token>[^&]+)|oauth_token_secret=(?<secret>[^&]+)|oauth_verifier=(?<verifier>[^&]+)"); return new OAuthTokenResponse { Token = matchedValues.Groups["token"].Value, TokenSecret = matchedValues.Groups["secret"].Value, VerificationString = matchedValues.Groups["verifier"].Value }; }
private List<TwitterEntity> GetLatestTweets(string handle) { List<TwitterEntity> tweets = new List<TwitterEntity>(); #region Twitter Library Setup OAuthTokens oaccesstkn = new OAuthTokens(); string consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"]; string consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"]; oaccesstkn.AccessToken = ConfigurationManager.AppSettings["TwitterAccessToken"]; oaccesstkn.AccessTokenSecret = ConfigurationManager.AppSettings["TwitterAccessSecret"]; ; oaccesstkn.ConsumerKey = consumerKey; oaccesstkn.ConsumerSecret = consumerSecret; #endregion try { #region Get Tweets From Twitter WebRequestBuilder webRequest = new WebRequestBuilder(new Uri(string.Format(ConfigurationManager.AppSettings["TwitterUrl"], handle, 500)), HTTPVerb.GET, oaccesstkn); string responseText; using (var response = webRequest.ExecuteRequest()) { using (var reader = new StreamReader(response.GetResponseStream())) { responseText = reader.ReadToEnd(); } } var brr = Encoding.UTF8.GetBytes(responseText); var streamReader = new StreamReader(new MemoryStream(brr)); var serializer = new DataContractJsonSerializer(typeof(SearchResults)); var tweetsResponse = (SearchResults)serializer.ReadObject(streamReader.BaseStream); streamReader.Close(); #endregion foreach (var mmTweetData in tweetsResponse.Results) { var tweetId = mmTweetData.Id.ToString(); try { var myTweet = new TwitterEntity { RowKey = Guid.NewGuid().ToString(), TwitterId = tweetId, TwitterIdString = mmTweetData.Id_Str, TextMessage = mmTweetData.Text, Source = mmTweetData.Source, FromUser = mmTweetData.Source, FromUserId = mmTweetData.ToUserName, ProfileImageUrl = mmTweetData.User.ProfileImageUrl, ProfileSecureImageUrl = mmTweetData.User.ProfileImageUrlHttps, ReplyUserId = mmTweetData.User.FromUserId.ToString(), ReplyScreenName = mmTweetData.User.FromUser, ResultType = mmTweetData.SearchMetaData.ResultType, LanguageCode = mmTweetData.SearchMetaData.IsoLanguageCode, Created_At = ParseTwitterDateTime(mmTweetData.CreatedAt), Status = "-1" }; tweets.Add(myTweet); } catch (Exception) { } } } catch (Exception) { } return tweets; }
/// <summary> /// Adds the OAuth Echo header to the supplied web request. /// </summary> /// <param name="request">The request.</param> /// <param name="tokens">The tokens.</param> public static HttpRequestMessage AddOAuthEchoHeader(HttpRequestMessage request, OAuthTokens tokens) { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/1/account/verify_credentials.json"), HttpMethod.Post, tokens); builder.PrepareRequest(); request.Headers.Add("X-Verify-Credentials-Authorization", builder.GenerateAuthorizationHeader()); request.Headers.Add("X-Auth-Service-Provider", "https://api.twitter.com/1/account/verify_credentials.json"); return request; }
/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static async Task<OAuthTokenResponse> AccessTokensAsync(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OAuthTokenResponse response = new OAuthTokenResponse(); try { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HttpMethod.Post, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); HttpResponseMessage httpresponse = await builder.ExecuteRequestAsync(); string responseBody = await httpresponse.Content.ReadAsStringAsync(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (responseBody.Contains("user_id=")) response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return response; }
/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static OAuthTokenResponse GetAccessTokens(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } OAuthTokenResponse response = new OAuthTokenResponse(); try { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HTTPVerb.POST, new OAuthTokens() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); string responseBody = new StreamReader(builder.ExecuteRequest().GetResponseStream()).ReadToEnd(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return response; }
/// <summary> /// Adds the OAuth Echo header to the supplied web request. /// </summary> /// <param name="request">The request.</param> /// <param name="tokens">The tokens.</param> public static void AddOAuthEchoHeader(WebRequest request, OAuthTokens tokens) { WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"), HTTPVerb.POST, tokens); builder.PrepareRequest(); request.Headers.Add("X-Verify-Credentials-Authorization", builder.GenerateAuthorizationHeader()); request.Headers.Add("X-Auth-Service-Provider", "https://api.twitter.com/1.1/account/verify_credentials.json"); }
/// <summary> /// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns> public static OAuthTokenResponse GetAccessTokens(string consumerKey, string consumerSecret, string username, string password) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException("username"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } var response = new OAuthTokenResponse(); try { var builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HTTPVerb.POST, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Parameters.Add("x_auth_username", username); builder.Parameters.Add("x_auth_password", password); builder.Parameters.Add("x_auth_mode", "client_auth"); var responseBody = string.Empty; using (var request = builder.ExecuteRequest()) using (var responseStream = request.GetResponseStream()) { if (responseStream != null) { using (var streamReader = new StreamReader(responseStream)) { responseBody = streamReader.ReadToEnd(); } } } response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; if (responseBody.Contains("user_id=")) { response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); } response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } return(response); }
/// <summary> /// Gets the access token. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="requestToken">The request token.</param> /// <param name="verifier">The pin number or verifier string.</param> /// <param name="proxy">The proxy.</param> /// <returns> /// An <see cref="OAuthTokenResponse"/> class containing access token information. /// </returns> public static OAuthTokenResponse GetAccessToken(string consumerKey, string consumerSecret, string requestToken, string verifier, WebProxy proxy) { if (string.IsNullOrEmpty(consumerKey)) { throw new ArgumentNullException("consumerKey"); } if (string.IsNullOrEmpty(consumerSecret)) { throw new ArgumentNullException("consumerSecret"); } if (string.IsNullOrEmpty(requestToken)) { throw new ArgumentNullException("requestToken"); } WebRequestBuilder builder = new WebRequestBuilder( new Uri("https://api.twitter.com/oauth/access_token"), HTTPVerb.GET, new OAuthTokens { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret }); builder.Proxy = proxy; if (!string.IsNullOrEmpty(verifier)) { builder.Parameters.Add("oauth_verifier", verifier); } builder.Parameters.Add("oauth_token", requestToken); string responseBody; try { HttpWebResponse webResponse = builder.ExecuteRequest(); responseBody = new StreamReader(webResponse.GetResponseStream()).ReadToEnd(); } catch (WebException wex) { throw new TwitterizerException(wex.Message, wex); } OAuthTokenResponse response = new OAuthTokenResponse(); response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value; response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value; response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture); response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value; return response; }
public void ProcessRequest(HttpContext context) { StringBuilder log = new StringBuilder(); string screenName = ""; try { string query = ""; UriBuilder urlBuilder = new UriBuilder("https://api.twitter.com/" + context.Server.UrlDecode(context.Request.QueryString["query"])); // Adds query strings to the url. // some headers may not be copied because they can't be used with clients other than twitter foreach (var queryString in context.Request.QueryString.AllKeys) { switch (queryString) { case "u": case "p": case "query": case "earned": case "pc": break; default: query += string.Format("&{0}={1}", queryString, context.Request.QueryString[queryString]); break; } } if (query.Length > 1) query = query.Substring(1); urlBuilder.Query = query; log.AppendLine(query); log.AppendLine("URL: " + urlBuilder.Uri.ToString()); OAuthTokens tokens = new OAuthTokens(); tokens.ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"]; tokens.ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"]; JToken accessToken; String userFileName = context.Server.MapPath("/App_Data/Users/" + context.Request.QueryString["u"] + "." + context.Request.QueryString["p"]); if (File.Exists(userFileName)) { using (StreamReader str = new StreamReader(userFileName)) { accessToken = JObject.Parse(str.ReadToEnd()); ; } tokens.AccessToken = (string)accessToken.SelectToken("AccessToken"); tokens.AccessTokenSecret = (string)accessToken.SelectToken("AccessSecret"); screenName = (string)accessToken.SelectToken("ScreenName"); log.AppendLine("User FOUND!"); } else { log.AppendLine("User NOT FOUND"); context.Response.StatusCode = 404; return; } //check if the request is xAuth, if it is, simulates the xAuth result for fooling Twitter for iPhone. if (context.Request.QueryString["query"].Contains("oauth/access_token")) { string xAuthResponse = string.Format("oauth_token={0}&oauth_token_secret={1}&user_id={2}&screen_name={3}&x_auth_expires=0", (string)accessToken.SelectToken("AccessToken"), (string)accessToken.SelectToken("AccessSecret"), (string)accessToken.SelectToken("UserId"), (string)accessToken.SelectToken("ScreenName")); context.Response.Write(xAuthResponse); screenName = (string)accessToken.SelectToken("ScreenName"); return; } HTTPVerb verb = HTTPVerb.GET; switch (context.Request.HttpMethod) { case "GET": verb = HTTPVerb.GET; break; case "POST": verb = HTTPVerb.POST; break; case "DELETE": verb = HTTPVerb.DELETE; break; } if (context.Request.Headers["Authorization"] == null) { tokens = null; log.AppendLine("Request NOT authenticated"); } WebRequestBuilder webreq = new WebRequestBuilder(urlBuilder.Uri, verb, tokens); webreq.Multipart = (context.Request.ContentType.Contains("multipart")); if (verb != HTTPVerb.GET) { // adds body parameters to request foreach (var key in context.Request.Form.AllKeys) { webreq.Parameters.Add(key, context.Request.Form[key]); } foreach (var fileKey in context.Request.Files.AllKeys) { webreq.Parameters.Add(fileKey, context.Request.Form[fileKey]); } } ServicePointManager.Expect100Continue = false; HttpWebRequest req = webreq.PrepareRequest(); try { HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); log.AppendLine("get Response"); StreamReader strReader = new StreamReader(resp.GetResponseStream()); String response = strReader.ReadToEnd(); if (ConfigurationManager.AppSettings["debugMode"] == "true") log.AppendLine(response); // replaces images url to use TwiX to load them response = Regex.Replace(response, @"(((http:\\/\\/www)|(http:\\/\\/)|(https:\\/\\/www)|(https:\\/\\/)|(www))[-a-zA-Z0-9@:%_\\\+.~#?&//=]+)\.(jpg|jpeg|gif|png|bmp|tiff|tga|svg)", delegate(Match match) { string v = match.ToString(); return ConfigurationManager.AppSettings["baseUrl"] + "image/" + shFunctions.encryptBase64Url(DES.Encrypt(v.Replace(@"\/", "/").Replace("_normal", ""), shFunctions.key) + ".jpg"); }); strReader.Close(); context.Response.ClearContent(); context.Response.Write(response); } catch (WebException webex) { if (webex.Status == WebExceptionStatus.ProtocolError) { context.Response.StatusCode = (int)((HttpWebResponse)webex.Response).StatusCode; } log.AppendLine("ERROR: " + webex.Message); return; } } catch (Exception ee){ log.AppendLine("Error: "+ ee.Message); log.AppendLine("stack: " + ee.StackTrace); } if (ConfigurationManager.AppSettings["log"] == "true") writeLogToFile(log.ToString(), screenName, context.Request.HttpMethod, context); //throw new Exception(context.Request.QueryString.ToString()); }