protected Common.Http.HttpResponse OAuthExecute(HttpRequestBuilder builder) { var auth = OAuthRequest.ForProtectedResource(builder.Method.ToString(), null, null, Settings.AccessToken, Settings.AccessTokenSecret); var request = builder.Build(); request.LogResponseContent = true; // we need the url without the query to sign auth.RequestUrl = request.Url.SetQuery(null).FullUri; if (builder.Method == HttpMethod.GET) { auth.Parameters = builder.QueryParams.ToDictionary(x => x.Key, x => x.Value); } else if (builder.Method == HttpMethod.POST) { auth.Parameters = builder.FormData.ToDictionary(x => x.Name, x => Encoding.UTF8.GetString(x.ContentData)); } var header = GetAuthorizationHeader(auth); request.Headers.Add("Authorization", header); return(_httpClient.Execute(request)); }
public dynamic Get(string endpoint) { //Make a protected resource call! this.client = OAuthRequest.ForProtectedResource("GET", this.consumer_key, this.consumer_secret, this.access_token, this.access_secret); //INSERT API Endpoint: this.client.RequestUrl = this.baseUrl + endpoint; //client.RequestUrl = baseUrl + "api/2/ping"; // Using URL query authorization string auth = this.client.GetAuthorizationQuery(); var url = this.client.RequestUrl + "?" + auth; var request = (HttpWebRequest)WebRequest.Create(url); //request3.ContentType = "application/json; charset=utf-8"; var response = (HttpWebResponse)request.GetResponse(); //Console.WriteLine(StreamToString(response3.GetResponseStream())); string json = StreamToString(response.GetResponseStream()); //Read the JSON from the string. JsonTextReader reader = new JsonTextReader(new StringReader(json)); //Serialize the JSON text. JsonSerializer se = new JsonSerializer(); //Deserialize the text and place in dynamic type, for easy manipulation. dynamic parsedData = se.Deserialize(reader); return(parsedData); }
private string GetAuthorizationHeader(Uri uri) { OAuthRequest client = OAuthRequest.ForProtectedResource("GET", "qLT42Pa4Pm7FxY4v7fqtBw", "s49oOJabVbS305j5yMVWcHOp3YX9XExl8pUHEv9g", "39523825-pCBfpmVcbyopUEXtwdOmMERq7VMtPk937YKO911tj", "E2EpHYquZTRJ3NYLK9JYeGN0jGD5P8jH9bQHtdFb7JI"); client.RequestUrl = uri.AbsoluteUri; var authorizationHeader = client.GetAuthorizationHeader(); return(authorizationHeader); }
public Task <HttpResponseMessage> GetResponse(string url, User user) { var client = OAuthRequest.ForProtectedResource("GET", user.ConsumerKey, user.ConsumerSecret, user.TokenValue, user.TokenSecret); client.RequestUrl = URL_PREFIX + url; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", client.GetAuthorizationHeader()); return(httpClient.GetAsync(client.RequestUrl)); }
static void Main(string[] args) { Console.WriteLine("Enter the Tweet ID: "); string tweetID = Console.ReadLine(); // no error checking here! // convenient to load keys and tokens from a config file for testing // edit .env.sample (and rename to .env) to add your keys and tokens (no quotation marks) DotNetEnv.Env.Load(); string CONSUMER_KEY = System.Environment.GetEnvironmentVariable("CONSUMER_KEY"); string CONSUMER_TOKEN = System.Environment.GetEnvironmentVariable("CONSUMER_TOKEN"); string ACCESS_TOKEN = System.Environment.GetEnvironmentVariable("ACCESS_TOKEN"); string ACCESS_TOKEN_SECRET = System.Environment.GetEnvironmentVariable("ACCESS_TOKEN_SECRET"); // this is the endpoint we will be calling StringBuilder apiPath = new StringBuilder("https://api.twitter.com"); apiPath.Append("/2/tweets"); apiPath.AppendFormat("?ids={0}", tweetID); apiPath.Append("&tweet.fields=attachments,author_id,context_annotations,created_at,entities,geo,id,in_reply_to_user_id,lang,possibly_sensitive,public_metrics,referenced_tweets,source,text,withheld"); apiPath.Append("&media.fields=duration_ms,height,media_key,preview_image_url,type,url,width"); apiPath.Append("&expansions=attachments.poll_ids,attachments.media_keys,author_id,geo.place_id,in_reply_to_user_id,referenced_tweets.id"); apiPath.Append("&poll.fields=duration_minutes,end_datetime,id,options,voting_status"); apiPath.Append("&place.fields=contained_within,country,country_code,full_name,geo,id,name,place_type"); apiPath.Append("&user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld"); string REQUEST_URL = apiPath.ToString(); // if you would like to compare to v1.1 then this alternative REQUEST_URL does that for Tweet ID 20 // string REQUEST_URL = "https://api.twitter.com/labs/2/tweets/20?tweet.fields=author_id,created_at,entities,source,public_metrics,lang,geo&expansions=author_id&user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,url,username,verified,public_metrics"; // Create a new connection to the OAuth server, with a helper method OAuthRequest client = OAuthRequest.ForProtectedResource("GET", CONSUMER_KEY, CONSUMER_TOKEN, ACCESS_TOKEN, ACCESS_TOKEN_SECRET); client.RequestUrl = REQUEST_URL; // add HTTP header authorization string auth = client.GetAuthorizationHeader(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl); request.Headers.Add("Authorization", auth); Console.WriteLine("\nCalling " + REQUEST_URL + "\n"); // make the call and print the string value of the response JSON HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string strResponse = reader.ReadToEnd(); Console.WriteLine(strResponse); // we have a string (JSON) }
public static bool ScheduleTweet(ITwitterAccount account) { try { string GET_REQUEST_URL = "https://api.twitter.com/1.1/statuses/update.json?status=Hello%20world"; OAuthRequest client = OAuthRequest.ForProtectedResource("POST", YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, account.OAuthToken, account.OAuthTokenSecret); client.RequestUrl = GET_REQUEST_URL; client.Method = "POST"; string auth = client.GetAuthorizationHeader(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl); request.Headers.Add("Authorization", auth); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; Console.WriteLine("Calling " + GET_REQUEST_URL); using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write("status=Hello%20world"); } // make the call and print the string value of the response JSON HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string strResponse = reader.ReadToEnd(); ScheduleTweetPOST(account); return(true); } catch (WebException ex) { using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) { var response = reader.ReadToEnd(); Console.WriteLine(response); } return(false); } catch (Exception ex) { Console.WriteLine(ex); return(false); } }
private string GetOAuthHeader(string url, string httpMethod, NameValueCollection parameters = null) { Configuration configuration = _configurationService.Configuration; string consumerKey = configuration.OAuthConsumerKey; string consumerSecret = configuration.OAuthConsumerSecret; string token = configuration.OAuthToken; string tokenSecret = configuration.OAuthTokenSecret; OAuthRequest oauthRequest = OAuthRequest.ForProtectedResource(httpMethod, consumerKey, consumerSecret, token, tokenSecret); oauthRequest.RequestUrl = url; return(oauthRequest.GetAuthorizationHeader(parameters != null ? parameters : new NameValueCollection())); }
public async Task <JObject> GetUser() { var client = OAuthRequest.ForProtectedResource( "GET", Resources.ConsumerKey, Resources.ConsumerSecret, AccessToken.AccessToken, AccessToken.AccessTokenSecret); client.RequestUrl = Resources.UserUrl; string url = string.Format("{0}?{1}", client.RequestUrl, client.GetAuthorizationQuery()); return(ToJson(await Tools.GetStringResponse(url))); }
public TwitterVerifyResult VerifyCredentials() { OAuthRequest oAuth = OAuthRequest.ForProtectedResource("GET", TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, Token, Secret); oAuth.RequestUrl = TWITTER_BASE_URL; var auth = oAuth.GetAuthorizationQuery(); var uri = new Uri(oAuth.RequestUrl + auth); var client = new HttpClient(); var response = client.GetAsync(uri).Result; if (response.IsSuccessStatusCode) { var content = response.Content.ReadAsStringAsync().Result; return(JsonConvert.DeserializeObject <TwitterVerifyResult>(content)); } return(null); }
/// <summary> /// Signs a request to the Breezy API with an OAuth token /// </summary> private void SignOAuthRequest(HttpClient httpClient, OAuthToken accessToken, HttpMethod method, string endpoint, IDictionary <string, string> parameters = null) { var request = OAuthRequest.ForProtectedResource(method.ToString().ToUpperInvariant(), _clientKey, _clientSecret, accessToken.Token, accessToken.TokenSecret); request.Method = method.ToString().ToUpperInvariant(); request.RequestUrl = _apiUri.AbsoluteUri + endpoint; var authHeader = parameters != null ? request.GetAuthorizationHeader(parameters) : request.GetAuthorizationHeader(); httpClient.DefaultRequestHeaders.Remove("Authorization"); httpClient.DefaultRequestHeaders.Add("Authorization", authHeader); }
public void UpdateStatus(string message, TwitterSettings settings) { var oAuthRequest = OAuthRequest.ForProtectedResource("POST", settings.ConsumerKey, settings.ConsumerSecret, settings.AccessToken, settings.AccessTokenSecret); oAuthRequest.RequestUrl = "https://api.twitter.com/1.1/statuses/update.json"; var customParams = new Dictionary <string, string> { { "status", message.EncodeRFC3986() } }; var request = GetRequest(oAuthRequest, customParams); request.Headers.ContentType = "application/x-www-form-urlencoded"; request.SetContent(Encoding.ASCII.GetBytes(GetCustomParametersString(customParams))); ExecuteRequest(request); }
protected Common.Http.HttpResponse OAuthGet(HttpRequestBuilder builder) { var auth = OAuthRequest.ForProtectedResource(builder.Method.ToString(), null, null, Settings.AccessToken, Settings.AccessTokenSecret); var request = builder.Build(); request.LogResponseContent = true; // we need the url without the query to sign auth.RequestUrl = request.Url.SetQuery(null).FullUri; auth.Parameters = builder.QueryParams.ToDictionary(x => x.Key, x => x.Value); var header = GetAuthorizationHeader(auth); request.Headers.Add("Authorization", header); return(_httpClient.Get(request)); }
public static string GetUserInfo(AvansOauthHelperOptions options, OauthToken accesToken) { OAuthRequest client = OAuthRequest.ForProtectedResource("GET", options.AvansClientId, options.AvansSecret, accesToken.Token, accesToken.Secret); client.RequestUrl = "https://publicapi.avans.nl/oauth/people/@me"; // Using URL query authorization to get the request token string auth = client.GetAuthorizationQuery(); var url = client.RequestUrl + "?" + auth; var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); Stream receiveStream = response.GetResponseStream(); StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); string body = reader.ReadToEnd(); return(body); }
public static bool InvalidateAccount(ITwitterAccount account) { try { string REQUEST_URL = $"https://api.twitter.com/1.1/oauth/invalidate_token?oauth_token={account.OAuthToken}"; OAuthRequest client = OAuthRequest.ForProtectedResource("POST", YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, account.OAuthToken, account.OAuthTokenSecret); client.RequestUrl = REQUEST_URL; client.Method = "POST"; string auth = client.GetAuthorizationHeader(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl); request.Headers.Add("Authorization", auth); request.Method = "POST"; Console.WriteLine("Calling " + REQUEST_URL); // make the call and print the string value of the response JSON HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string strResponse = reader.ReadToEnd(); var queryParams = HttpUtility.ParseQueryString(strResponse); return(true); } catch (WebException ex) { using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream())) { var response = reader.ReadToEnd(); Console.WriteLine(response); } return(false); } catch (Exception ex) { Console.WriteLine(ex); return(false); } }
public async Task <T> Get <T>(string requestUrl, string data = null) { var authHead = OAuthRequest.ForProtectedResource("GET", ApiCredentials.ConsumerKey, ApiCredentials.ConsumerSecret, AccessCredentials.AccessToken, AccessCredentials.AccessTokenSecret); authHead.RequestUrl = Endpoint + requestUrl; if (data != null) { authHead.RequestUrl = authHead.RequestUrl + data; } HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", authHead.GetAuthorizationHeader()); var req = await httpClient.GetAsync(authHead.RequestUrl); var res = await req.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(res)); }
private static void ScheduleTweetPOST(ITwitterAccount account) { string REQUEST_URL = $"https://ads-api.twitter.com/7/accounts/{account.UserId}/scheduled_tweets?"; OAuthRequest client = OAuthRequest.ForProtectedResource("POST", YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, account.OAuthToken, account.OAuthTokenSecret); client.RequestUrl = REQUEST_URL; client.Method = "POST"; string auth = client.GetAuthorizationHeader(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl); request.Headers.Add("Authorization", auth); Console.WriteLine("Calling " + REQUEST_URL); // make the call and print the string value of the response JSON HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string strResponse = reader.ReadToEnd(); var queryParams = HttpUtility.ParseQueryString(strResponse); }