Ejemplo n.º 1
0
        public static string TweeterCall(string url, string consumerKey, string consumerSecret)
        {
            OAuthRequest client = new OAuthRequest
            {
                Method          = "GET",
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = url,
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string         auth    = client.GetAuthorizationHeader();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            var    encoding     = Encoding.UTF8;
            var    reader       = new System.IO.StreamReader(response.GetResponseStream(), encoding);
            string responseText = reader.ReadToEnd();

            reader.Dispose();
            return(responseText);
        }
Ejemplo n.º 2
0
        private string InitialRequestHeaderString(string uuid, string formatType)
        {
            NameValueCollection nameValueCollection = new NameValueCollection();

            nameValueCollection.Add("x_uuid", uuid);
            int num = this.initURL.IndexOf('?');

            if (num != -1)
            {
                string   text  = this.initURL.Substring(num + 1);
                string[] array = text.Split(new char[]
                {
                    '&'
                });
                foreach (string text2 in array)
                {
                    string[] array3 = text2.Split(new char[]
                    {
                        '='
                    });
                    nameValueCollection.Add(array3[0], array3[1]);
                }
            }
            OAuthRequest oauthRequest = new OAuthRequest
            {
                Method         = "POST",
                ConsumerKey    = this.counsumerKey,
                ConsumerSecret = this.counsumerSecret,
                RequestUrl     = string.Format(this.initURL, "request_token")
            };

            return(oauthRequest.GetAuthorizationHeader(nameValueCollection));
        }
Ejemplo n.º 3
0
        public string CreateBrowseableUrl()
        {
            // this is the endpoint we will be calling
            string REQUEST_URL = "https://api.twitter.com/oauth/request_token?oauth_callback=oob";

            // Create a new connection to the OAuth server, with a helper method
            OAuthRequest client = OAuthRequest.ForRequestToken(YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, "oob");

            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("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);

            RequestToken = queryParams["oauth_token"];

            // answer: oauth_token=6E9q-gAAAAABFGpUAAABc0TQsN4&oauth_token_secret=FwJdADlFg2H4niPoE0M3WOUROmElhcal&oauth_callback_confirmed=true
            return($"https://api.twitter.com/oauth/authorize?oauth_token={RequestToken}");
        }
Ejemplo n.º 4
0
        private void Sign(HttpRequestMessage msg, OAuthRequest req)
        {
            req.SignatureMethod = OAuthSignatureMethod.HmacSha1;
            req.ConsumerKey     = _consumer.Key;
            req.ConsumerSecret  = _consumer.Secret;
            req.RequestUrl      = msg.RequestUri.GetLeftPart(UriPartial.Path);
            req.Method          = msg.Method.Method;
            req.Version         = "1.0";

            var args = msg.RequestUri.ParseQueryString();

            if (msg.Content != null)
            {
                var contentType = msg.Content.Headers.ContentType;
                if (contentType != null && string.Equals("application/x-www-form-urlencoded", contentType.MediaType, StringComparison.OrdinalIgnoreCase))
                {
                    var body = new FormDataCollection(msg.Content.ReadAsStringAsync().Result);
                    foreach (var item in body)
                    {
                        args.Add(item.Key, item.Value);
                    }
                }
            }

            msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), req.GetAuthorizationHeader(args).TrimEnd(','));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Make an API request with OAuth 1.0
        /// </summary>
        public async Task <string> requestAPIOAuthAsync(string url, Method method)
        {
            //Generate OAuthRequest data (library used: OAuth.DotNetCore from Robert Hargreaves)
            OAuthRequest client = new OAuthRequest
            {
                Method             = method.ToString(),
                SignatureTreatment = OAuthSignatureTreatment.Escaped,
                SignatureMethod    = OAuthSignatureMethod.HmacSha1,
                ConsumerKey        = consumerKey,
                ConsumerSecret     = consumerSecret,
                Token       = tokenValue,
                TokenSecret = tokenSecret,
                RequestUrl  = url,
                Version     = "1.0"
            };

            // Format authorization as header string
            string auth = client.GetAuthorizationHeader();

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod(client.Method), client.RequestUrl))
                {
                    request.Headers.TryAddWithoutValidation("Authorization", auth);

                    var response = await httpClient.SendAsync(request);

                    return(response.Content.ReadAsStringAsync().Result);
                }
            }
        }
Ejemplo n.º 6
0
        // Haven't actually tested this out yet
        public async Task ReconnectAccount()
        {
            var authRequest = new OAuthRequest
            {
                Method          = "GET",
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = ConsumerKey,
                ConsumerSecret  = ConsumerSecret,
                Token           = AccessToken,
                TokenSecret     = AccessTokenSecret,
                RequestUrl      = ReconnectUrl,
                Version         = OAuthVersion
            };

            var client = ReconnectUrl.WithHeaders(new
            {
                Accept        = AcceptType,
                Authorization = authRequest.GetAuthorizationHeader()
            });

            try
            {
                await client.GetAsync();
            }
            catch (FlurlHttpException ex)
            {
                throw new QuickBooksException("Unable to reconnect account.", ex.Message);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets the Authorization Header for the supplied url.
        /// </summary>
        /// <param name="requestUrl">The request url for signing.</param>
        /// <returns>A string that can be used as the value for the "Authorization" header of an HTTP request.</returns>
        public string GetAuthHeadersForRequestByType(string requestUrl, string type)
        {
            if (string.IsNullOrEmpty(serviceConfig.AccessToken))
            {
                try
                {
                    GetToken();
                }
                catch (AcsApiException ex)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    // return non-specific error and destroy call stack
                    throw new Exception(GenericAuthorizationErrorMessage);
                }
            }

            // Creating a new instance directly
            var client = new OAuthRequest
            {
                Method          = type,
                Type            = OAuthRequestType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = serviceConfig.ConsumerKey,
                ConsumerSecret  = serviceConfig.ConsumerSecret,
                Token           = serviceConfig.AccessToken,
                TokenSecret     = serviceConfig.AccessTokenSecret,
                RequestUrl      = requestUrl
            };

            // Using HTTP header authorization
            return(client.GetAuthorizationHeader(ParseParamCollection(new Uri(requestUrl))));
        }
Ejemplo n.º 8
0
        public ITwitterAccount ConnectAccount(string pin)
        {
            string REQUEST_URL = $"https://api.twitter.com/oauth/access_token?oauth_token={RequestToken}&oauth_verifier={pin}";

            OAuthRequest client = OAuthRequest.ForAccessToken(YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, RequestToken, pin);

            client.RequestUrl = REQUEST_URL;

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

            return(new TwitterAccount(queryParams["oauth_token"], queryParams["oauth_token_secret"], queryParams["user_id"], queryParams["screen_name"]));
        }
Ejemplo n.º 9
0
        //Get Request Token
        public async Task <RequestTokenResponse> GetRequestToken()
        {
            var requestTokenResponse = new RequestTokenResponse();


            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;
            var callbackUrl    = "http://localhost:4200/login";

            client.DefaultRequestHeaders.Accept.Clear();

            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/oauth/request_token",
                Version         = "1.0a",
                Realm           = "twitter.com",
                CallbackUrl     = callbackUrl
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);



            try
            {
                var content = new StringContent("", Encoding.UTF8, "application/json");

                using (var response = await client.PostAsync(oauthClient.RequestUrl, content))
                {
                    response.EnsureSuccessStatusCode();

                    var responseString = response.Content.ReadAsStringAsync()
                                         .Result.Split("&");


                    requestTokenResponse = new RequestTokenResponse
                    {
                        oauth_token              = responseString[0],
                        oauth_token_secret       = responseString[1],
                        oauth_callback_confirmed = responseString[2]
                    };
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(requestTokenResponse);
        }
Ejemplo n.º 10
0
        //Get Access Token
        public async Task <UserModelDto> GetAccessToken(string token, string oauthVerifier)
        {
            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;

            var accessTokenResponse = new UserModelDto();

            client.DefaultRequestHeaders.Accept.Clear();

            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                Type            = OAuthRequestType.AccessToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/oauth/access_token",
                Token           = token,
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);


            try
            {
                var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("oauth_verifier", oauthVerifier)
                });

                using (var response = await client.PostAsync(oauthClient.RequestUrl, content))
                {
                    response.EnsureSuccessStatusCode();

                    //twiiter responds with a string concatenated by &
                    var responseString = response.Content.ReadAsStringAsync()
                                         .Result.Split("&");

                    //split by = to get acual values
                    accessTokenResponse = new UserModelDto
                    {
                        Token       = responseString[0].Split("=")[1],
                        TokenSecret = responseString[1].Split("=")[1],
                        UserId      = responseString[2].Split("=")[1],
                        Username    = responseString[3].Split("=")[1]
                    };
                }
            }
            catch (Exception ex)
            {
            }

            return(accessTokenResponse);
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        private NameValueCollection OAuthQuery(OAuthRequest oAuthRequest)
        {
            var auth    = oAuthRequest.GetAuthorizationHeader();
            var request = new Common.Http.HttpRequest(oAuthRequest.RequestUrl);

            request.Headers.Add("Authorization", auth);
            var response = _httpClient.Get(request);

            return(HttpUtility.ParseQueryString(response.Content));
        }
Ejemplo n.º 13
0
        private HttpRequest GetRequest(OAuthRequest oAuthRequest, Dictionary <string, string> customParams)
        {
            var auth    = oAuthRequest.GetAuthorizationHeader(customParams);
            var request = new HttpRequest(oAuthRequest.RequestUrl);

            request.Headers.Add("Authorization", auth);

            request.Method = oAuthRequest.Method == "POST" ? HttpMethod.Post : HttpMethod.Get;

            return(request);
        }
Ejemplo n.º 14
0
        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)
        }
Ejemplo n.º 15
0
        public async Task <SearchTweetResponseModel> SearchTweets(SearchTweetRequestModel requestModel)
        {
            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;

            var tweetsResponse = new SearchTweetResponseModel();

            client.DefaultRequestHeaders.Accept.Clear();

            var json = JsonSerializer.Serialize(requestModel, new JsonSerializerOptions {
                IgnoreNullValues = true
            });

            var reqContent = new StringContent(json, Encoding.UTF8, "application/json");


            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/1.1/tweets/search/30day/dev.json",
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);

            try
            {
                using var httpResponse = await client.PostAsync(oauthClient.RequestUrl, reqContent);

                httpResponse.EnsureSuccessStatusCode();

                var contentStream = await httpResponse.Content.ReadAsStreamAsync();

                tweetsResponse = await JsonSerializer.DeserializeAsync <SearchTweetResponseModel>(contentStream);

                //var check = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
            }

            return(tweetsResponse);
        }
Ejemplo n.º 16
0
        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);
            }
        }
Ejemplo n.º 17
0
        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()));
        }
Ejemplo n.º 18
0
        public void GetAuthorizationHeaderThrowsExceptionWhenOAuthTokenIsNullOrEmptyString(string tokenValue)
        {
            var oAuthRequest = new OAuthRequest
            {
                Method         = "GET",
                Token          = tokenValue,
                ConsumerSecret = "secret",
                ConsumerKey    = "key",
                ClientUsername = "******",
                ClientPassword = "******",
                RequestUrl     = "http://url",
                Type           = OAuthRequestType.AccessToken
            };

            Assert.Throws <ArgumentException>(() => oAuthRequest.GetAuthorizationHeader());
        }
Ejemplo n.º 19
0
        // bbax: oAuth step 1: request_token
        private HttpWebResponse RequestToken(OAuthRequest client)
        {
            // Using HTTP header authorization
            var auth    = client.GetAuthorizationHeader();
            var request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);
            var response = (HttpWebResponse)request.GetResponse();

            if (response == null)
            {
                throw new AcsApiException(AcsApiError.CouldNotAuthToken);
            }
            InvokeLog("Client token " + response);
            return(response);
        }
Ejemplo n.º 20
0
        public void GetAuthorizationHeaderContainsOAuthToken(bool expectedResult, string tokenValue, OAuthRequestType oAuthRequestType)
        {
            var oAuthRequest = new OAuthRequest
            {
                Method         = "GET",
                Token          = tokenValue,
                ConsumerSecret = "secret",
                ConsumerKey    = "key",
                ClientUsername = "******",
                ClientPassword = "******",
                RequestUrl     = "http://url",
                Type           = oAuthRequestType
            };

            Assert.AreEqual(expectedResult, oAuthRequest.GetAuthorizationHeader().Contains("oauth_token"));
        }
Ejemplo n.º 21
0
        private void GetAuthorizationHeader(string url, string method, out string scheme, out string parameter)
        {
            BricklinkClientConfiguration.Instance.ValidateThrowException();

            var request = new OAuthRequest(BricklinkClientConfiguration.Instance.ConsumerKey,
                                           BricklinkClientConfiguration.Instance.ConsumerSecret,
                                           BricklinkClientConfiguration.Instance.TokenValue,
                                           BricklinkClientConfiguration.Instance.TokenSecret,
                                           url,
                                           method);

            var header          = request.GetAuthorizationHeader();
            var schemeParameter = header.Split(' ');

            scheme    = schemeParameter[0];
            parameter = schemeParameter[1];
        }
Ejemplo n.º 22
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var client = new OAuthRequest
            {
                Method          = request.Method.Method,
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = _auth.ConsumerKey,
                ConsumerSecret  = _auth.ConsumerSecret,
                RequestUrl      = request.RequestUri.ToString(),
                Version         = "1.0a"
            };
            var auth = client.GetAuthorizationHeader();

            request.Headers.Add("Authorization", auth);

            return(base.SendAsync(request, cancellationToken));
        }
Ejemplo n.º 23
0
        private HttpWebResponse RequestFinal(OAuthRequest client, string accessToken, string oauthVerifier, string cdomain, string consumerCookies)
        {
            client.Token       = accessToken;
            client.Type        = OAuthRequestType.AccessToken;
            client.Verifier    = oauthVerifier;
            client.RequestUrl  = serviceConfig.ServerRoot + AcsApiClientConfig.AccessUrl;
            client.CallbackUrl = null;
            client.TokenSecret = HttpUtility.UrlDecode(client.TokenSecret);
            var auth = client.GetAuthorizationHeader();

            var accessTokenRequest = (HttpWebRequest)WebRequest.Create(serviceConfig.ServerRoot + AcsApiClientConfig.AccessUrl);

            accessTokenRequest.Method = "GET";
            accessTokenRequest.Headers.Add("Authorization", auth);
            accessTokenRequest.CookieContainer = new CookieContainer();
            //accessTokenRequest.CookieContainer.Add(new Cookie(ConsumerTypeIdKey, ConsumerTypeValue) { Domain = cdomain });

            CookieCollection newRequiredCookies = new CookieCollection();

            try
            {
                newRequiredCookies = AcsApiSetCookieHeaderParser.GetAllCookiesFromHeader(consumerCookies,
                                                                                         new Uri(serviceConfig.ServerRoot).Host);
            }
            catch (Exception e)
            {
                throw new AcsApiException("Could not parse cookie for final request!");
            }
            RefreshCookies(newRequiredCookies, accessTokenRequest);

            accessTokenRequest.AllowAutoRedirect = false;

            HttpWebResponse accessTokenResponse = null;

            try
            {
                accessTokenResponse = (HttpWebResponse)accessTokenRequest.GetResponse();
            }
            catch (WebException wex)
            {
                throw new AcsApiException(AcsApiError.ServerError.ToString(), wex);
            }
            return(accessTokenResponse);
        }
Ejemplo n.º 24
0
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                OAuthRequest OAuthclient = new OAuthRequest
                {
                    Method          = "GET",
                    Type            = OAuthRequestType.RequestToken,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ConsumerKey     = "OwnAccount",
                    ConsumerSecret  = "OwnAccount",
                    Token           = "token",
                    TokenSecret     = "token-secret",
                    RequestUrl      = "https://api-sandbox.tradeshift.com/tradeshift/rest/external/network/connections",
                    Version         = "1.0",
                };

                var auth = OAuthclient.GetAuthorizationHeader();
                Console.WriteLine(auth);

                client.BaseAddress = new Uri("https://api-sandbox.tradeshift.com/tradeshift/rest/external/network/connections");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("X-Tradeshift-TenantId", "ts-tennantid");
                client.DefaultRequestHeaders.Add("Authorization", auth);

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("");

                if (response.IsSuccessStatusCode)
                {
                    Tradeshift res = await response.Content.ReadAsAsync <Tradeshift>();

                    Console.WriteLine("{0}", res.itemCount);
                }
                else
                {
                    Console.WriteLine("No success response..");
                }

                Console.WriteLine("HTTP Status: {0}", response.StatusCode);
                Console.ReadLine();
            }
        }
Ejemplo n.º 25
0
        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);
            }
        }
        private string BuildOAuthHeader(RequestData requestData, string fullUrl, IDictionary <string, string> parameters)
        {
            var oauthRequest = new OAuthRequest
            {
                Type           = OAuthRequestType.ProtectedResource,
                RequestUrl     = fullUrl,
                Method         = requestData.HttpMethod.ToString().ToUpperInvariant(),
                ConsumerKey    = _oAuthCredentials.ConsumerKey,
                ConsumerSecret = _oAuthCredentials.ConsumerSecret,
            };

            if (!string.IsNullOrEmpty(requestData.OAuthToken))
            {
                oauthRequest.Token       = requestData.OAuthToken;
                oauthRequest.TokenSecret = requestData.OAuthTokenSecret;
            }

            return(oauthRequest.GetAuthorizationHeader(parameters));
        }
Ejemplo n.º 27
0
        //Get User Details
        public async Task <TwitterUserDetails> VerifyCredentials(string token, string tokenSecret)
        {
            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;

            client.DefaultRequestHeaders.Accept.Clear();

            var userDetails = new TwitterUserDetails();

            var oauthClient = new OAuthRequest
            {
                Method          = "GET",
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                Token           = token,
                TokenSecret     = tokenSecret,
                RequestUrl      = "https://api.twitter.com/1.1/account/verify_credentials.json",
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);

            try
            {
                using (var response = await client.GetAsync(oauthClient.RequestUrl))
                {
                    response.EnsureSuccessStatusCode();

                    userDetails = JsonConvert.DeserializeObject <TwitterUserDetails>(response.Content.ReadAsStringAsync().Result);
                }
            }
            catch (Exception ex)
            {
            }

            return(userDetails);
        }
Ejemplo n.º 28
0
        public void Can_get_request_token_with_http_header()
        {
            var client = new OAuthRequest
            {
                Method         = "GET",
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                RequestUrl     = string.Format(_baseUrl, "request_token"),
                CallbackUrl    = _callbackUrl
            };

            var auth = client.GetAuthorizationHeader();

            var request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                var reader  = new StreamReader(response.GetResponseStream());
                var content = reader.ReadToEnd();
            }
            catch (System.Exception ex)
            {
                if (ex is WebException wex)
                {
                    var reader = new StreamReader(wex.Response.GetResponseStream());
                    _ = reader.ReadToEnd();
                }

                throw;
            }

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }
Ejemplo n.º 29
0
        public async Task <QuickBooksUser> GetCurrentUser()
        {
            var authRequest = new OAuthRequest
            {
                Method          = "GET",
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = ConsumerKey,
                ConsumerSecret  = ConsumerSecret,
                Token           = AccessToken,
                TokenSecret     = AccessTokenSecret,
                RequestUrl      = CurrentUserUrl,
                Version         = OAuthVersion
            };

            var client = CurrentUserUrl.WithHeaders(new
            {
                Accept        = AcceptType,
                Authorization = authRequest.GetAuthorizationHeader()
            });

            try
            {
                var response = await client.GetAsync();

                var xml = XmlHelper.ParseXmlString(response.Content.ReadAsStringAsync().Result);
                return(new QuickBooksUser
                {
                    FirstName = xml["FirstName"],
                    LastName = xml["LastName"],
                    EmailAddress = xml["EmailAddress"],
                    ScreenName = xml["ScreenName"],
                    IsVerified = bool.Parse(xml["IsVerified"])
                });
            }
            catch (FlurlHttpException ex)
            {
                throw new QuickBooksException("Unable to retrieve current user.", ex.Message);
            }
        }
Ejemplo n.º 30
0
        public void Can_get_request_token_with_http_header()
        {
            var client = new OAuthRequest
                             {
                                 Method = "GET",
                                 ConsumerKey = _consumerKey,
                                 ConsumerSecret = _consumerSecret,
                                 RequestUrl = string.Format(BaseUrl, "request_token")
                             };

            var auth = client.GetAuthorizationHeader();
            
            var request = (HttpWebRequest) WebRequest.Create(client.RequestUrl);
            
            request.Headers.Add("Authorization", auth);

            var response = (HttpWebResponse) request.GetResponse();

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }
Ejemplo n.º 31
0
        public void Can_get_request_token_with_http_header()
        {
            var client = new OAuthRequest
            {
                Method         = "GET",
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                RequestUrl     = string.Format(BaseUrl, "request_token")
            };

            var auth = client.GetAuthorizationHeader();

            var request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);

            var response = (HttpWebResponse)request.GetResponse();

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }