/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="username">The username.</param> /// <param name="returnUrl">The return URL.</param> /// <returns></returns> public override Boolean Authenticate(HttpRequest request, out string username, out string returnUrl) { username = string.Empty; returnUrl = _returnUrl; string oauthVerifier = request.QueryString["oauth_verifier"]; string callbackOAuthToken = request.QueryString["oauth_token"]; // Verify callback oauth token matches previous request token if (callbackOAuthToken == _oauthToken) { try { string consumerKey = GetAttributeValue("ConsumerKey"); string consumerSecret = GetAttributeValue("ConsumerSecret"); // Get an access token for the authenticated request token that was returned in the callback URL var restClient = new RestClient("https://api.twitter.com") { Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, _oauthToken, _oauthTokenSecret, oauthVerifier) }; var restRequest = new RestRequest("oauth/access_token", Method.POST);;; var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { NameValueCollection r = HttpUtility.ParseQueryString(restResponse.Content); string accessToken = r["oauth_token"]; string accessTokenSecret = r["oauth_token_secret"]; // Get information about the person who logged in restRequest = new RestRequest("1.1/account/verify_credentials.json", Method.GET); restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret); restRequest.AddParameter("skip_status", true); restRequest.AddParameter("include_email", true); restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { dynamic twitterUser = JObject.Parse(restResponse.Content); username = GetTwitterUser(twitterUser, accessToken); } } } catch (Exception ex) { ExceptionLogService.LogException(ex, HttpContext.Current); } } return(!string.IsNullOrWhiteSpace(username)); }
public virtual IRestResponse Post(string url) { var request = CreateRestRequest(Method.POST, url); var client = new RestClient(_baseUrl); if (_ticket != null) { client.Authenticator = OAuth1Authenticator.ForProtectedResource(_ticket.ConsumerKey, _ticket.ConsumerSecret, _ticket.AccessToken, _ticket.AccessTokenSecret); } var response = client.Execute(request); return(response); }
/// <summary> /// request to post votes on a suggestion /// </summary> /// <param name="subdomain">the site's subdomain</param> /// <param name="forumId">the forumId</param> /// <param name="consumerKey">your conusmer key</param> /// <param name="consumerSecret">your consumer secret</param> /// <param name="accessToken">the user's access token</param> /// <param name="accessTokenSecret">the user's access token secret</param> /// <param name="suggestionId">the suggestion's id</param> /// <param name="votes">the number of votes that should be applied to the suggestion</param> /// <returns>response for the request to post votes on a suggestion</returns> private async Task <IRestResponse> PostVoteOnSuggestionResponse(string subdomain, string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, int forumId, int suggestionId, int votes) { _client = new RestClient(string.Format("https://{0}.uservoice.com/api/v1/forums/{1}/suggestions/{2}/", subdomain, forumId, suggestionId)); _client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret); RestRequest request = new RestRequest("votes.json", HttpMethod.Post); request.AddHeader("If-Modified-Since", DateTime.Now.ToUniversalTime().ToString("R")); request.AddParameter("to", votes); return(await _client.Execute(request)); }
/// <summary> /// Create the TwitterClient object /// </summary> /// <param name="auth">OAuth1 authentication for the client</param> public TwitterClient(OAuth auth) { twitterApiClient = new RestClient("https://api.twitter.com/1.1"); twitterUploadClient = new RestClient("https://upload.twitter.com/1.1"); IAuthenticator authenticator = OAuth1Authenticator.ForProtectedResource( auth.consumerKey, auth.consumerSecret, auth.accessToken, auth.accessTokenSecret ); twitterApiClient.Authenticator = authenticator; twitterUploadClient.Authenticator = authenticator; }
// public static object ServiceStack { get; private set; } static void Main(string[] args) { var client = new RestClient("https://apiv3.geovictoria.com/api"); //Url del servicio string consumerkey = "1dd229"; //Key publica string consumersecret = "43dd1bb2"; //Key privada client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerkey, consumersecret, string.Empty, string.Empty); var request = new RestRequest("/AttendanceBook/GetAttendance", Method.POST); //PunchesList/currentWeek. Siempre hágalo mediante POST // var request = new RestRequest("/User/List", Method.POST); // /User: Operation. Always use "POST" // var request = new RestRequest("/Punch/List/", Method.POST); //PunchesList/currentWeek. Siempre hágalo mediante POST request.RequestFormat = DataFormat.Json; /* * request.AddJsonBody(new * { * Range = "100771896,100898055,101612856,102305531,102659384,104764282,104872123,105967136,107458204,107638504,10915041K,111369496,114710105,114758574,11542890K,115541730,117777073,11881312K,120543792,120997742,122349101,122381676,122542319,122571653,123600274,125056598,12632037K,12635942K,126547110,126706065,12793245K,128314520,128535411,130294456,131067798,132397376,132746559,13462311K,134820098,135479314,137249243,139370732,139391691,140368504,140555576,141364456,14176201K,142428466,143624153,143823466,145351650,145668670,147346794,150466504,151675468,151723012,15326726K,153482225,153522863,153744173,154260021,15443125K,154669671,155837012,156610615,156975133,157034472,157998412,15800433K,158007118,158010143,158223155,159410536,159551679,159680843,160764163,160838914,161139114,161471852,163290367,163545608,164218724,16459520K,165174860,165297199,165466349,165615530,165694953,166374006,166381657,166472814,166952581,166965837,167097367,169209316,169942587,171484472,171510503,172326668,172879888", * from = "20191203050000", * to = "20191203235900", * includeAll = 0 * });*/ request.AddJsonBody(new { Range = "173020465,173052804,173410476,173422024,173743769,173747136,173763506,173892926,174440336,174974799,175645853,175792996,175797203,176687339,176997079,177397229,177460877,177509698,177671312,177695580,177706949,177707821,178591460,178711229,180723250,180789812,180797459,180889051,180892370,180915435,18150904K,181701366,182483524,183276530,183283251,184429497,184511630,184686929,185698289,186223802,18626357K,186278895,18629565K,188469361,188490840,188510604,188586937,188619169,188802729,189135041,190945219,191645197,191875079,192334640,192846420,193112889,193127398,193432999,19370803K,193788963,194199570,194411537,195278067,195444676,195479410,195482586,19882383K,198837261,198858900,200496795,200528050,224992904,231880267,236671305,237357329,244390226,252023372,254529931,257124398,258188993,259022428,259866332,261664240,262744876,265775705,265819125,267964335,46738268,61871942,63809810,67025695,68880122,70390779,76298858,76869987,76878749,81685193,8302173K,87170241,87752682,89630096,9297250K,94746191,96125577,97686394", from = "20191203050000", to = "20191203235900", includeAll = 0 }); // request.AddJsonBody(new { Range = "customRange", from = "20190801060000", to = "20190802235900" }); var response = client.Execute(request); var content = response.Content; //Obtener la respuesta // var records =Object; Console.WriteLine(content); //Ver respuesta en pantalla System.IO.File.WriteAllText(@"salidaVictoria.json", content); // Console.WriteLine("Press any key to continue..."); // Console.ReadKey(); System.IO.File.WriteAllText(@"c:\temp\salidaVictoria.json", content); //var records = ServiceStack.Text.CsvSerializer.SerializeToCsv(content); //System.IO.File.WriteAllText(@"c:\temp\salidaVictoria.cvs", records); //jsonStringToCSV(content); dynamic array = JsonConvert.DeserializeObject(content); List <string> lineas = ((JArray)array).Select(node => string.Join(",", ((JObject)node).Properties().Select(p => p.Value))).ToList(); System.IO.File.WriteAllLines(@"C:\temp\resultado1_3.csv", lineas); Console.ReadKey(); }
public static List <Device> GetDevices() { var client = new RestClient(BaseUrl); client.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicKey, PrivateKey, Token, TokenSecret); var request = new RestRequest("json/devices/list", Method.GET); var response = client.Execute(request); Devices deviceList = JsonConvert.DeserializeObject <Devices>(response.Content); deviceList.device.RemoveAll(x => x.name.ElementAt(0) == 'S'); return(deviceList.device); }
protected RestClient GetClient() { var client = new RestClient(_apiUri); client.AddDefaultHeader(_contentTypeHeaderWithUnderscore ? "Content_Type" : "Content-Type", "application/json"); client.ClearHandlers(); client.AddHandler("application/json", _jsonSerializer); client.Authenticator = OAuth1Authenticator.ForProtectedResource( _consumerKey, _consumerSecret, _accessToken, _accessTokenSecret); return(client); }
/// <summary> /// Returns the logged in User object /// </summary> /// <param name="type"></param> /// <param name="filter"></param> /// <param name="maxUpdates"></param> public async Task <User> GetUserID() { client.Authenticator = OAuth1Authenticator.ForProtectedResource(API_KEY, OAUTH_SECRET, UserSettings.Settings.OAuthAccessToken, UserSettings.Settings.OAuthAccessTokenSecret); await apiSemaphore.WaitAsync(); var request = new RestRequest("api/auth_user", Method.GET); var response = await client.ExecuteAsync(request); ApiCooldown(); var result = DeserializeResponse(response.Content.ToString()); return(result.User); }
//private const int COOLDOWN_MILLISECONDS = 1000; //private RestClient client; //private IGoodReadsAuthenticator authenticator; //private readonly SemaphoreSlim apiSemaphore = new SemaphoreSlim(1, 1); //private User authenticatedUser; //private bool justRefreshedUser = false; //public List<UserShelf> GoodreadsUserShelves { get; set; } //private bool justRefreshedShelves = false; //public Reviews GoodreadsReviews { get; set; } //public bool justRefreshedReviews = false; //public GoodReadsAPI(IGoodReadsAuthenticator authenticator) //{ // this.authenticator = authenticator; // authenticator.AuthenticationCompleted += authenticator_AuthenticationCompleted; // client = new RestClient(Urls.BaseUrl); //} //async void authenticator_AuthenticationCompleted(object sender, EventArgs e) //{ // await CompleteAuthentication(); //} #region API Calls ///// <summary> ///// Authenticates the user using the Web Authentication Broker ///// </summary> //public async Task<bool> Authenticate() //{ // // If we have an session key already no need to do anything // if (UserSettings.Settings.IsUserAuthenticated) // return true; // // set up get request tokens // client.Authenticator = OAuth1Authenticator.ForRequestToken(API_KEY, OAUTH_SECRET); // // Request token // await apiSemaphore.WaitAsync(); // var request = new RestRequest("/oauth/request_token", Method.GET); // var requestResponse = await client.ExecuteAsync(request); // ApiCooldown(); // // Parse oauth token and token secret // var querystring = HttpUtility.ParseQueryString(requestResponse.Content); // if (querystring != null && querystring.Count == 2) // { // UserSettings.Settings.OAuthToken = querystring["oauth_token"]; // UserSettings.Settings.OAuthTokenSecret = querystring["oauth_token_secret"]; // } // else return false; // // authenticate // string goodreadsURL = "https://www.goodreads.com/oauth/authorize?oauth_token=" + UserSettings.Settings.OAuthToken; // WebAuthenticationResult result = await authenticator.Authenticate(WebAuthenticationOptions.None, new Uri(goodreadsURL), WebAuthenticationBroker.GetCurrentApplicationCallbackUri()); // // success // if (result != null && result.ResponseStatus == WebAuthenticationStatus.Success) // { // return await CompleteAuthentication(); // } // return false; //} //public async Task<bool> CompleteAuthentication() //{ // // set up get // client.Authenticator = OAuth1Authenticator.ForAccessToken(API_KEY, OAUTH_SECRET, UserSettings.Settings.OAuthToken, UserSettings.Settings.OAuthTokenSecret); // //request access token // await apiSemaphore.WaitAsync(); // var request = new RestRequest("oauth/access_token", Method.GET); // var accessResponse = await client.ExecuteAsync(request); // ApiCooldown(); // // parse oauth access token and token secrets // var querystring = HttpUtility.ParseQueryString(accessResponse.Content); // if (querystring != null && querystring.Count == 2) // { // UserSettings.Settings.OAuthAccessToken = querystring["oauth_token"]; // UserSettings.Settings.OAuthAccessTokenSecret = querystring["oauth_token_secret"]; // } // else return false; // // if we don't have a user ID yet, go fetch it // if (String.IsNullOrEmpty(UserSettings.Settings.GoodreadsUserID)) // { // var user = await GetUserID(); // UserSettings.Settings.GoodreadsUserID = user.Id; // UserSettings.Settings.GoodreadsUserLink = user.Link; // UserSettings.Settings.GoodreadsUsername = user.Name; // } // authenticatedUser = await GetUserInfo(UserSettings.Settings.GoodreadsUserID); // UserSettings.Settings.GoodreadsUserImageUrl = authenticatedUser.Image_url; // UserSettings.Settings.GoodreadsUserSmallImageUrl = authenticatedUser.Small_image_url; // justRefreshedUser = true; // GoodreadsUserShelves = await GetShelvesList(); // justRefreshedShelves = true; // GoodreadsReviews = await GetShelfBooks(); // justRefreshedReviews = true; // return true; //} ///// <summary> ///// Returns the logged in User object ///// </summary> ///// <param name="type"></param> ///// <param name="filter"></param> ///// <param name="maxUpdates"></param> //public async Task<User> GetUserID() //{ // client.Authenticator = OAuth1Authenticator.ForProtectedResource(API_KEY, OAUTH_SECRET, UserSettings.Settings.OAuthAccessToken, UserSettings.Settings.OAuthAccessTokenSecret); // await apiSemaphore.WaitAsync(); // var request = new RestRequest("api/auth_user", Method.GET); // var response = await client.ExecuteAsync(request); // ApiCooldown(); // var result = DeserializeResponse(response.Content.ToString()); // return result.User; //} /// <summary> /// Returns a users notifications /// </summary> /// <param name="type"></param> /// <param name="filter"></param> /// <param name="maxUpdates"></param> public async Task <Notifications> GetNotifications(int page = 1) { client.Authenticator = OAuth1Authenticator.ForProtectedResource(API_KEY, OAUTH_SECRET, UserSettings.Settings.OAuthAccessToken, UserSettings.Settings.OAuthAccessTokenSecret); await apiSemaphore.WaitAsync(); var request = new RestRequest("notifications.xml", Method.GET); var response = await client.ExecuteAsync(request); ApiCooldown(); var result = DeserializeResponse(response.Content.ToString()); return(result.Notifications); }
/// <summary> /// Creates a new instance of the JiraRestClient class. /// </summary /// <param name="url">Url to the JIRA server.</param> /// <param name="consumerKey">Consumer key to use for OAuth1 authentication.</param> /// <param name="consumerSecret">Consumer secret to use for OAuth1 authentication. Should be private key in xml format.</param> /// <param name="accessToken">User access token to use for authenticating API requests.</param> /// <param name="accessTokenSecret">User access token secret to use for authenticating API requests.</param> /// <param name="settings">Settings to configure the rest client.</param> public JiraRestClient(string url, string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, JiraRestClientSettings settings = null) { url = url.EndsWith("/") ? url : url += "/"; _clientSettings = settings ?? new JiraRestClientSettings(); _restClient = new RestClient(url) { Proxy = _clientSettings.Proxy }; if (!String.IsNullOrEmpty(consumerKey) && !String.IsNullOrEmpty(consumerSecret) && !String.IsNullOrEmpty(accessToken) && !String.IsNullOrEmpty(accessTokenSecret)) { this._restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret, OAuthSignatureMethod.RsaSha1); } }
/// <summary> /// the response for the all KB topics request /// </summary> /// <param name="subdomain">the site's subdomain</param> /// <param name="consumerKey">your consumer key</param> /// <param name="consumerSecret">your consumer secret</param> /// <param name="page">the page number</param> /// <param name="perPage">the number of articles per page</param> /// <returns>IRestResponse containing the requested data</returns> private async Task <IRestResponse> GetAllTopicsResponse(string subdomain, string consumerKey, string consumerSecret, int page = 1, int perPage = 10) { _client.BaseUrl = new Uri(string.Format("https://{0}.uservoice.com/api/v1/", subdomain)); _client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, null, null); RestRequest request = new RestRequest("topics.json", HttpMethod.Get); request.AddHeader("If-Modified-Since", DateTime.Now.ToUniversalTime().ToString("R")); request.AddParameter("page", page); request.AddParameter("per_page", perPage); return(await _client.Execute(request)); }
//-------------------------------------------------------------------------- // // Internal Methods // //-------------------------------------------------------------------------- /// <summary> /// contains all of the oauth magic, makes the http request and returns raw json /// </summary> /// <param name="parameters">hash array of qs parameters</param> /// <returns>plain text json response from the api</returns> protected Task <T> makeRequest <T>(string area, string id, Dictionary <string, string> parameters) { // build the url with parameters var url = area; if (!String.IsNullOrEmpty(id)) { url += "/" + Uri.EscapeDataString(id); } // restsharp FTW! var client = new RestClient(rootUri); client.Authenticator = OAuth1Authenticator.ForProtectedResource(options.ConsumerKey, options.ConsumerSecret, options.AccessToken, options.AccessTokenSecret); var request = new RestRequest(url, Method.GET); if (parameters != null) { string[] keys = parameters.Keys.ToArray(); foreach (string k in keys) { request.AddParameter(k, parameters[k]); } } var tcs = new TaskCompletionSource <T>(); var handle = client.ExecuteAsync(request, response => { if (response.StatusCode == HttpStatusCode.NotFound) { tcs.SetResult(default(T)); } else { try { T results = JsonConvert.DeserializeObject <T>(response.Content); tcs.SetResult(results); } catch (Exception ex) { tcs.SetException(ex); } } }); return(tcs.Task); }
private VerifyCredentialsResult VerifyCredentials(AccessTokenResult accessTokenResult) { if (accessTokenResult == null) { throw new ArgumentNullException("accessTokenResult"); } if (string.IsNullOrEmpty(accessTokenResult.AccessToken)) { throw new ArgumentException("accessTokenResult.AccessToken"); } if (string.IsNullOrEmpty(accessTokenResult.AccessTokenSecret)) { throw new ArgumentException("accessTokenResult.AccessTokenSecret"); } IRestResponse <VerifyCredentialsResult> response; try { var restClient = _restClientFactory.CreateRestClient(BaseUrl); restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(_consumerKey, _consumerSecret, accessTokenResult.AccessToken, accessTokenResult.AccessTokenSecret); var request = new RestRequest("1.0/user"); var responsex = restClient.Execute(request); } catch (Exception exception) { throw new AuthenticationException( "Failed to retrieve VerifyCredentials json data from the Twitter Api.", exception); } //if (response == null || // response.StatusCode != HttpStatusCode.OK || // response.Data == null) //{ // throw new AuthenticationException( // string.Format( // "Failed to retrieve VerifyCredentials json data OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}", // response == null ? "-- null response --" : response.StatusCode.ToString(), // response == null ? string.Empty : response.StatusDescription)); //} //return response.Data; return(null); }
public void LoadOAuthAuthenticator(OAuthSettings settings) { if (settings.AccessToken.IsNullOrWhitespace() || settings.AccessTokenSecret.IsNullOrWhitespace()) { throw new AuthenticationException("Missing access token or secret. Cannot create Authenticator"); } var consumer = new ConsumerCredentials(settings.ConsumerKey, settings.ConsumerSecret); client_.Authenticator = OAuth1Authenticator.ForProtectedResource( consumer.Key, consumer.Secret, settings.AccessToken, settings.AccessTokenSecret, OAuthSignatureMethod.RsaSha1); }
public InfraworksRestService(OAuthService oauthSvc) { this.m_OAuthService = oauthSvc; if (m_client == null) { m_client = new RestClient(iwRestSvcUrl); OAuth1Authenticator authenticator = OAuth1Authenticator.ForProtectedResource( m_OAuthService.ConsumerKey, m_OAuthService.ConsumerSecret, m_OAuthService.AccessToken, m_OAuthService.AccessTokenSecret); m_client.Authenticator = authenticator; } }
public bool LogIn(Logfile logfile) { //Log in to GoodReads to authenticate user //Get OAuth tokens var oauthRequestToken = new RestRequest("oauth/request_token"); var response = client.Execute(oauthRequestToken); var qs = HttpUtility.ParseQueryString(response.Content); var oauthToken = qs["oauth_token"]; var oauthTokenSecret = qs["oauth_token_secret"]; logfile.WriteLine("Goodreads API request:", oauthRequestToken.Body); //Construct url for user to login to var oauthAuthorise = new RestRequest("oauth/authorize"); oauthAuthorise.AddParameter("oauth_token", oauthToken); oauthAuthorise.AddParameter("oauth_token_secret", oauthTokenSecret); response = client.Execute(oauthAuthorise); var url = client.BuildUri(oauthAuthorise).ToString(); //Get user to login online Console.WriteLine("Please log in at: {0}\nPress any key to continue.", url); Console.ReadLine(); client.Authenticator = OAuth1Authenticator.ForAccessToken(apiKey, apiSecret, oauthToken, oauthTokenSecret); var oauthAccessToken = new RestRequest("oauth/access_token"); response = client.Execute(oauthAccessToken); if ((int)response.StatusCode != 200) { return(false); } qs = HttpUtility.ParseQueryString(response.Content); var accessToken = qs["oauth_token"]; var accessTokenSecret = qs["oauth_token_secret"]; //Get user information client.Authenticator = OAuth1Authenticator.ForProtectedResource(apiKey, apiSecret, accessToken, accessTokenSecret); var authUser = new RestRequest("api/auth_user", DataFormat.Xml); var authResponse = ExecuteGetRequest <AuthResponse>(authUser, logfile); userId = authResponse.Data.user.id; userName = authResponse.Data.user.name; return(true); }
public async Task ProtectedResourceQueryAsPostComplexUtf8() { var auth = OAuth1Authenticator.ForProtectedResource("consumer-key", "consumer-secret", "access-token", "access-token-secret"); auth.RandomNumberGenerator = new MyRandomNumberGenerator(); auth.CreateTimestampFunc = () => ToUnixTime(new DateTime(2015, 11, 8, 11, 12, 13)).ToString(); var client = new TestRestClient(); var request = new RestRequest("test", Method.POST); request.AddParameter("status", "😈❤️😍🎉😜 😜👯🍻🎈🎤🎮🚀🌉✨"); await auth.PreAuthenticate(client, request, null); var header = request.Parameters.FirstOrDefault(x => x.Name == "Authorization"); Assert.NotNull(header); Assert.Equal("OAuth oauth_consumer_key=\"consumer-key\",oauth_nonce=\"abcdefghijklmnop\",oauth_signature=\"rXtn0AUYLME80k3dLcizx3wNLxk%3D\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1446981133\",oauth_token=\"access-token\",oauth_version=\"1.0\"", (string)header.Value); }
public string GetTransactions(string accessToken, string tokenSecret, string leagueKey) { _client.Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, Secret, accessToken, tokenSecret); var request = new RestRequest("league/{leagueKey}/transactions;type=trade"); request.AddUrlSegment("leagueKey", leagueKey); request.AddJsonParam(); var response = Retry.Do <IRestResponse>(() => ExecuteRequest(_client, request), TimeSpan.FromSeconds(1), 10); //var data = JObject.Parse(response.Content); //var transactions = data["fantasy_content"]["league"][0]["transactions"]; return(response.Content); }
public Tuple <SettingsRoot, string> GetLeagueSettings(string accessToken, string tokenSecret, string leagueKey) { _client.Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, Secret, accessToken, tokenSecret); var request = new RestRequest("league/{leagueKey}/settings", Method.GET); request.AddUrlSegment("leagueKey", leagueKey); request.AddJsonParam(); var response = Retry.Do <IRestResponse>(() => ExecuteRequest(_client, request), TimeSpan.FromSeconds(1), 10); //var data = JObject.Parse(response.Content); var settings = JsonConvert.DeserializeObject <SettingsRoot>(response.Content); return(Tuple.Create <SettingsRoot, string>(settings, response.Content)); //return settings; }
/// <summary> /// Returns the friend update feed for the logged in user /// </summary> /// <param name="type"></param> /// <param name="filter"></param> /// <param name="maxUpdates"></param> public async Task <Updates> GetFriendUpdates(string type, string filter, string maxUpdates) { string url = Urls.UpdatesFriends;// BASEURL + UPDATES + FRIENDS;// +type + filter + "&max_updates=" + maxUpdates + "&access_token=" + OAuthAccessToken; client.Authenticator = OAuth1Authenticator.ForProtectedResource(API_KEY, OAUTH_SECRET, UserSettings.Settings.OAuthAccessToken, UserSettings.Settings.OAuthAccessTokenSecret); await apiSemaphore.WaitAsync(); var request = new RestRequest("updates/friends.xml", Method.GET); var response = await client.ExecuteAsync(request); ApiCooldown(); GoodreadsResponse result = DeserializeResponse(response.Content.ToString()); return(result.Updates); }
public async Task ProtectedResourceQuerySimpleUtf8() { var auth = OAuth1Authenticator.ForProtectedResource("consumer-key", "consumer-secret", "access-token", "access-token-secret"); auth.RandomNumberGenerator = new MyRandomNumberGenerator(); auth.CreateTimestampFunc = () => ToUnixTime(new DateTime(2015, 11, 8, 11, 12, 13)).ToString(); var client = new TestRestClient(); var request = new RestRequest("test", Method.POST); request.AddParameter("status", "☺", ParameterType.QueryString); await auth.PreAuthenticate(client, request, null).ConfigureAwait(false); var header = request.Parameters.FirstOrDefault(x => x.Name == "Authorization"); Assert.NotNull(header); Assert.Equal("OAuth oauth_consumer_key=\"consumer-key\",oauth_nonce=\"abcdefghijklmnop\",oauth_signature=\"SIDMGnDWsGNw8XKV9WrrdAgynSE%3D\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1446981133\",oauth_token=\"access-token\",oauth_version=\"1.0\"", (string)header.Value); }
public List <Semester> GetUserCourses(string accessToken, string tokenSecret, User user) { Client.Authenticator = OAuth1Authenticator .ForProtectedResource(ConsumerKey, ConsumerSecret, accessToken, tokenSecret); var userDataRequest = new RestRequest("courses/user", Method.GET); var userDataResponse = Client.Execute(userDataRequest); if (!userDataResponse.IsSuccessful) { throw new Exception("Fetching usos data error"); } JObject json = JObject.Parse(userDataResponse.Content); var semesters = new List <Semester>(); foreach (var semJson in json["course_editions"].Children()) { var semester = new Semester() { Name = semJson.ToObject <JProperty>().Name }; semester.Courses = new List <Course>(); foreach (var courseJson in semJson.First.Children()) { var course = new Course() { Name = courseJson.Value <string>("course_id") }; semester.Courses.Add(course); } semesters.Add(semester); } if (user.UserRole != UserRole.Lecturer) { return(semesters); } var lecturerSemesters = GetUserCoursesAsLecturer(accessToken, tokenSecret, user); semesters = MergeSemesterData(semesters, lecturerSemesters, user.Id.Value); return(semesters); }
/// <summary> /// Sends a get request, returns result as a string /// </summary> /// <param name="url">Url to send to, relative to the BL base url</param> /// <returns>The result, as a string</returns> public string GetRequest(string url) { var client = new RestClient(Statics.ApiUrl) { Authenticator = OAuth1Authenticator.ForProtectedResource( Statics.ConsumerKey, Statics.ConsumerSecret, Statics.TokenValue, Statics.TokenSecret ) }; var request = new RestRequest(url); var response = client.Execute(request); return(response.Content); }
public byte[] GetByteArray(string url) { try { var request = CreateRestRequest(Method.GET, url); var client = new RestSharp.RestClient(_baseUrl); client.FollowRedirects = false; if (_ticket != null) { client.Authenticator = OAuth1Authenticator.ForProtectedResource(_ticket.ConsumerKey, _ticket.ConsumerSecret, _ticket.AccessToken, _ticket.AccessTokenSecret); } var responseData = client.DownloadData(request); return(responseData); } catch { throw; } }
public static IRestResponse <QuoteDto> GetQuote(EtOAuthConfig config, string symbols, DetailFlag detailFlag = DetailFlag.ALL) { var qClient = new RestClient { BaseUrl = new Uri(config.BaseUrl), Authenticator = OAuth1Authenticator.ForProtectedResource(config.ConsumerKey, config.ConsumerSecret, config.AccessToken, config.AccessSecret) }; var request = new RestRequest($"market/quote/{symbols}"); request.AddQueryParameter("detailFlag", detailFlag.ToString()); request.AddQueryParameter("requireEarningsDate", "true"); request.AddQueryParameter("skipMiniOptionsCheck", "true"); var response = qClient.Execute <QuoteDto>(request); return(response); }
/// <summary> /// the response for the search all KB request /// </summary> /// <param name="subdomain">the site's subdomain</param> /// <param name="consumerKey">your consumer key</param> /// <param name="consumerSecret">your consumer secret</param> /// <param name="query">your search query</param> /// <param name="page">the page number</param> /// <param name="perPage">the number of articles per page</param> /// <param name="filter">how the request response should be filtered</param> /// <param name="sort">the order in which the response should be sorted</param> /// <returns>IRestResponse containing the requested data</returns> private async Task <IRestResponse> SearchAllArticlesResponse(string subdomain, string consumerKey, string consumerSecret, string query, int page = 1, int perPage = 10, ArticlesFilter filter = ArticlesFilter.all, ArticlesSort sort = ArticlesSort.newest) { _client.BaseUrl = new Uri(string.Format("https://{0}.uservoice.com/api/v1/", subdomain)); _client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, null, null); RestRequest request = new RestRequest("search.json", HttpMethod.Get); request.AddHeader("If-Modified-Since", DateTime.Now.ToUniversalTime().ToString("R")); request.AddParameter("page", page); request.AddParameter("query", query); request.AddParameter("per_page", perPage); request.AddParameter("filter", filter); request.AddParameter("sort", sort); return(await _client.Execute(request)); }
/// <summary> /// Queries user info using corresponding service and data received by access token request. /// </summary> private string QueryUserInfo() { var client = _factory.CreateClient(UserInfoServiceEndpoint); client.Authenticator = OAuth1Authenticator.ForProtectedResource( Configuration.ClientId, Configuration.ClientSecret, AccessToken, AccessTokenSecret); var request = _factory.CreateRequest(UserInfoServiceEndpoint); BeforeGetUserInfo(new BeforeAfterRequestArgs { Client = client, Request = request, Configuration = Configuration }); return(client.ExecuteAndVerify(request).Content); }
public Session Login() { OAuth1Authenticator authenticator = OAuth1Authenticator.ForProtectedResource( m_OAuthService.ConsumerKey, m_OAuthService.ConsumerSecret, m_OAuthService.AccessToken, m_OAuthService.AccessTokenSecret); //must be HttpAuthorizationHeader here, authenticator.ParameterHandling = RestSharp.Authenticators.OAuth.OAuthParameterHandling.HttpAuthorizationHeader; m_client.Authenticator = authenticator; RestRequest request = new RestRequest("/api/v2/authentication/oxygen-login", Method.POST); request.RequestFormat = DataFormat.Json; request.AddHeader("content-type", "application/json"); request.AddHeader("accept", "application/json"); //The oxygen-login endpoint doesn’t read anything from the header. So the OAuth data you are putting in the header is unnecessary. //One of the annoyances I have with REST is that there are multiple channels for input. //You have the URL, the query string, the HTTP header, the HTTP body and the HTTP verb. Many times it’s not clear what data should go where. //The PLM API will favor putting data in the HTTP body whenever possible. OxygenCredentials cred = new OxygenCredentials(); cred.customerId = this.customerId.ToUpper(); //must be upper case?? Yes, must be UPPERCASE!! cred.validation = authenticator.GetAuthorizationHeader(); // using a revised version of restsharp, authenticator.ParameterHandling should be HttpAuthorizationHeader request.AddBody(cred); IRestResponse <Session> response = m_client.Execute <Session>(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { //save the cookies for latter use foreach (var cookie in response.Cookies) { Cookies.Add(cookie.Name, cookie.Value); } return(response.Data); } else { return(null); } }
public ActionResult MakeOAuthRequest(string accessToken, string accessTokenSecret, string endpointUri, string endpointAction) { OAuthProxyResponseModel retVal = new OAuthProxyResponseModel(); OAuthKeyConfiguration oauthConfiguration = OAuthKeyConfiguration.GetInstance(); RestClient restClient = new RestClient(endpointUri); restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(oauthConfiguration.ConsumerKey, oauthConfiguration.ConsumerSecret, accessToken, accessTokenSecret); string[] parameterItems = null; if (endpointAction.Contains("?")) { string[] actionElements = endpointAction.Split('?'); parameterItems = actionElements[1].Split('&'); endpointAction = actionElements[0]; } RestRequest request = new RestRequest(endpointAction, Method.GET); request.RequestFormat = DataFormat.Json; if (parameterItems != null) { for (int i = 0; i < parameterItems.Length; i++) { string[] parameterElements = parameterItems[i].Split('='); request.AddParameter(parameterElements[0], parameterElements[1]); } } IRestResponse response = restClient.Execute(request); if (response != null) { retVal.Response = response.Content; } return(View("MakeOAuthRequest", retVal)); }
// calismiyor public static string getTemplatev2() { string ret = ""; var client = new RestClient(url); client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumer_key, consumer_secret, token, token_secret); var request = new RestRequest("/v2/templates", Method.GET); //request.AddParameter("users", "1", ParameterType.GetOrPost); // request.AddParameter("category", "all",ParameterType.GetOrPost); var response = client.Execute(request); if (response != null && !string.IsNullOrWhiteSpace(response.Content)) { ret = response.Content; } return(ret); }