public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCollection parameters, string url) { ValidateProtectedResourceState(); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); // Include url parameters in query pool var uri = new Uri(url); var urlParameters = HttpUtility.ParseQueryString(uri.Query); allParameters.AddRange(urlParameters.AllKeys.Select(x => new WebPair(x !, urlParameters[x] !))); var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); var authParameters = GenerateAuthParameters(timestamp, nonce); allParameters.AddRange(authParameters); var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, allParameters); return(new OAuthParameters { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret), Parameters = authParameters }); }
private void getCar2GoAccounts(string token, string token_secret, DownloadStringCompletedEventHandler requestCallback) { var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/accounts"; var parameters = new WebParameterCollection(); parameters.Add("oauth_callback", "oob"); parameters.Add("oauth_signature_method", "HMAC-SHA1"); parameters.Add("oauth_token", token); parameters.Add("oauth_version", "1.0"); parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey); parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp()); parameters.Add("oauth_nonce", OAuthTools.GetNonce()); parameters.Add("format", "json"); parameters.Add("loc", Car2Go.City); //parameters.Add("test", "1"); var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters); var signature = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, token_secret); var requestParameters = OAuthTools.NormalizeRequestParameters(parameters); var requestUrl = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute); var webClient = new WebClient(); webClient.DownloadStringCompleted += requestCallback; webClient.DownloadStringAsync(requestUrl); }
public void GetNonce_Is_Threadsafe() { string nonce1 = string.Empty; string nonce2 = string.Empty; Thread thread1 = new Thread(() => { Thread.Sleep(100); nonce1 = OAuthTools.GetNonce(); }); Thread thread2 = new Thread(() => { Thread.Sleep(100); nonce2 = OAuthTools.GetNonce(); }); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); Assert.NotNull(nonce1); Assert.NotNull(nonce2); Assert.NotEmpty(nonce1); Assert.NotEmpty(nonce2); Assert.NotEqual(nonce1, nonce2); }
public void GetNonce_Creates_16_Byte_Nonce() { string nonce = OAuthTools.GetNonce(); Assert.NotNull(nonce); Assert.NotEmpty(nonce); Assert.Equal(NonceLength, nonce.Length); }
public async Task <string> buscarAlimento(string alimento) { const string baseURL = "http://platform.fatsecret.com/rest/server.api?"; const string consumerKey = "89a75f2dda9748d08cc87d573992fecb"; string signatureMethod = "HMAC-SHA1"; string timestamp = OAuthTools.GetTimestamp(); string nonce = OAuthTools.GetNonce(); const string version = "1.0"; const string method = "foods.search"; const string format = "json"; var normalizedParameters = "format=" + format + "&method=" + method + "&oauth_consumer_key=" + consumerKey + "&oauth_nonce=" + nonce + "&oauth_signature_method=" + signatureMethod + "&oauth_timestamp=" + timestamp + "&oauth_version=" + version + "&search_expression=" + "banana"; var httpMethod = "GET"; var encodedUri = OAuthTools.UrlEncodeStrict(baseURL.Substring(0, baseURL.Length - 1)); var encodedNormalizedParameters = OAuthTools.UrlEncodeStrict(normalizedParameters); var baseSignature = httpMethod + "&" + encodedUri + "&" + encodedNormalizedParameters; string signature; using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes("5e1b6dc6e9e84451bc265d633b9fc0de&"))) { byte[] hashPayLoad = hmac.ComputeHash(Encoding.ASCII.GetBytes(baseSignature)); signature = Convert.ToBase64String(hashPayLoad); } string fullURL = baseURL + normalizedParameters + "&oauth_signature=" + signature; String responseText = await Task.Run(() => { try { HttpWebRequest request = WebRequest.Create(fullURL) as HttpWebRequest; request.Method = "GET"; WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); return(new StreamReader(responseStream).ReadToEnd()); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } return(null); }); return(responseText); }
public void Can_generate_nonce() { var nonce = OAuthTools.GetNonce(); Assert.IsNotNull(nonce); Assert.IsTrue(nonce.Length == 16); Console.WriteLine(nonce); var next = OAuthTools.GetNonce(); Assert.AreNotEqual(nonce, next); Console.WriteLine(next); }
public void GetNonce_Creates_New_Nonce_Each_Run() { string nonce1 = OAuthTools.GetNonce(); string nonce2 = OAuthTools.GetNonce(); string nonce3 = OAuthTools.GetNonce(); Assert.NotNull(nonce1); Assert.NotNull(nonce2); Assert.NotNull(nonce3); Assert.NotEmpty(nonce1); Assert.NotEmpty(nonce2); Assert.NotEmpty(nonce3); Assert.NotEqual(nonce1, nonce2); Assert.NotEqual(nonce2, nonce3); Assert.NotEqual(nonce1, nonce3); }
public void Can_guarantee_random_nonces_in_succession() { var nonces = new List <string>(); for (var i = 0; i < 10000; i++) { var nonce = OAuthTools.GetNonce(); var timestamp = DateTime.Now; Console.WriteLine(nonce + ":" + timestamp); if (nonces.Contains(nonce)) { Assert.Fail("non-unique nonce seed generated"); } else { nonces.Add(nonce); } } }
/// <summary> /// Generates an OAuth signature to pass to an /// <see cref="IAuthenticator" /> for the purpose of requesting an /// unauthorized request token. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> /// <returns></returns> public OAuthParameters BuildRequestTokenInfo(string method, WebPairCollection parameters) { ValidateTokenRequestState(); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); var authParameters = GenerateAuthParameters(timestamp, nonce); allParameters.AddRange(authParameters); var signatureBase = OAuthTools.ConcatenateRequestElements(method, Ensure.NotNull(RequestTokenUrl, nameof(RequestTokenUrl)), allParameters); return(new OAuthParameters { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret), Parameters = authParameters }); }
/// <summary> /// Generates an OAuth signature to pass to an /// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials /// for an access token authorized by the user at the Service Provider site. /// </summary> /// <param name="method">The HTTP method for the intended request</param> /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param> public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPairCollection parameters) { ValidateClientAuthAccessRequestState(); var allParameters = new WebPairCollection(); allParameters.AddRange(parameters); var uri = new Uri(Ensure.NotNull(AccessTokenUrl, nameof(AccessTokenUrl))); var timestamp = OAuthTools.GetTimestamp(); var nonce = OAuthTools.GetNonce(); var authParameters = GenerateXAuthParameters(timestamp, nonce); allParameters.AddRange(authParameters); var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters); return(new OAuthParameters { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret), Parameters = authParameters }); }
public void Can_guarantee_random_nonces_in_succession_multithreaded() { const int threads = 16; const int totalNonces = 30000; const int noncesPerThread = totalNonces / threads; var nonces = new List <string>(); var noncesLock = new object(); var dupes = new List <string>(); var dupesLock = new object(); var sem = new Semaphore(0, threads); var ts = new ThreadStart(() => { sem.WaitOne(); try { var localNonces = new List <string>(); for (var i = 0; i < noncesPerThread; i++) { var nonce = OAuthTools.GetNonce(); localNonces.Add(nonce); } lock (nonces) { var localDupes = from s in nonces where localNonces.Contains(s) select s; if (localDupes.Any()) { lock (dupesLock) { dupes.AddRange(localDupes); } } nonces.AddRange(localNonces.Except(localDupes)); } } finally { sem.Release(); } }); var workerThreads = new Thread[threads]; for (var i = 0; i < threads; i++) { workerThreads[i] = new Thread(ts) { IsBackground = false, Name = "thread" + i }; workerThreads[i].Start(); } sem.Release(threads); foreach (var t in workerThreads) { t.Join(); } Assert.IsEmpty(dupes, "Found {0} duplicated nonces generated during test", dupes.Count); lock (noncesLock) { Assert.AreEqual(totalNonces, nonces.Count); } }
private void LoadBookedCars() { HasBooking = false; try { var token = (string)App.GetAppSetting("car2go.oauth_token"); var tokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret"); if (null == token || null == tokenSecret) { return; } const string car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/booking"; var parameters = new WebParameterCollection { { "oauth_callback", "oob" }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_token", token }, { "oauth_version", "1.0" }, { "oauth_consumer_key", consumerkey }, { "oauth_timestamp", OAuthTools.GetTimestamp() }, { "oauth_nonce", OAuthTools.GetNonce() }, { "format", "json" }, { "loc", City }, }; //parameters.Add("test", "1"); var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters); var signature = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, tokenSecret); var requestParameters = OAuthTools.NormalizeRequestParameters(parameters); var requestUrl = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute); var webClient = new WebClient(); webClient.OpenReadCompleted += (sender, args) => { try { if (0 == args.Result.Length) { return; } try { var serializer = new DataContractJsonSerializer(typeof(Car2GoBookingResult)); var bookingResult = (Car2GoBookingResult)serializer.ReadObject(args.Result); var car2GoCars = new List <Car2GoMarker>(); if (0 == bookingResult.ReturnValue.Code) { if (bookingResult.Booking.Length > 0) { lastBookedCarsUpdate = DateTime.Now; } foreach (var booking in bookingResult.Booking) { var car = booking.Vehicle; GeoCoordinate carPosition = null; try { carPosition = new GeoCoordinate(car.Position.Latitude, car.Position.Longitude); } catch {} var carInfo = new Car2GoMarker { model = ("CE" == car.EngineType) ? "C-Smart" : "Smart ElectricDrive", fuelState = car.Fuel, position = carPosition, licensePlate = car.NumberPlate, ID = car.VIN, exterior = car.Exterior, interior = car.Interior, isBooked = true, BookingId = bookingResult.Booking[0].BookingId, }; HasBooking = true; car2GoCars.Add(carInfo); } Markers = car2GoCars; if (null != Updated) { Updated(this, null); } } } catch (NullReferenceException) { } } catch (WebException) { } }; webClient.OpenReadAsync(requestUrl); } catch (Exception e) { Console.WriteLine(e); } }
public void Authenticate(IRestClient client, IRestRequest request) { var url = client.BuildUri(request).ToString(); // add body xauth arguments var arguments = new Dictionary <string, object>(); if (string.IsNullOrWhiteSpace(Token)) { arguments.Add("x_auth_username", Username); arguments.Add("x_auth_mode", "client_auth"); arguments.Add("x_auth_password", Password); foreach (var item in arguments) { request.AddParameter(item.Key, item.Value); } } else { foreach (var parameter in request.Parameters) { arguments.Add(parameter.Name, parameter.Value); } } var nonce = OAuthTools.GetNonce(); var signatureMethod = "HMAC-SHA1"; var timeStamp = OAuthTools.GetTimestamp(); var version = "1.0"; var oauthArguments = new Dictionary <string, string>(); oauthArguments.Add("oauth_signature_method", signatureMethod); oauthArguments.Add("oauth_nonce", nonce); oauthArguments.Add("oauth_consumer_key", ConsumerKey); oauthArguments.Add("oauth_timestamp", timeStamp); oauthArguments.Add("oauth_version", version); if (!string.IsNullOrWhiteSpace(Token)) { oauthArguments.Add("oauth_token", Token); } var mergedArguments = new Dictionary <string, object>(arguments); foreach (var item in oauthArguments) { mergedArguments.Add(item.Key, item.Value); } mergedArguments = mergedArguments.OrderBy(i => i.Key).ToDictionary(pair => pair.Key, pair => pair.Value); var signatureBase = String.Format("{0}&{1}&", Method.POST, OAuthTools.UrlEncodeRelaxed(url)); foreach (var item in mergedArguments) { var encodedKey = OAuthTools.UrlEncodeRelaxed(item.Key); string encodedValue; if (item.Value != null) { encodedValue = OAuthTools.UrlEncodeRelaxed(item.Value.ToString()); } else { encodedValue = string.Empty; } signatureBase += String.Format("{0}%3D{1}%26", encodedKey, encodedValue); } signatureBase = signatureBase.Substring(0, signatureBase.Length - 3); signatureBase = signatureBase.Replace("%40", "%2540"); // ugly hack for now... var signature = OAuthTools.GetSignature(signatureBase, ConsumerSecret, TokenSecret); // create authorization header var authHeader = "OAuth "; authHeader += string.Format("{0}=\"{1}\"", "oauth_signature", signature); foreach (var item in oauthArguments) { authHeader += string.Format(", {0}=\"{1}\"", item.Key, item.Value); } request.AddHeader("Authorization", authHeader); }
private void CreateCar2GoBooking(DownloadStringCompletedEventHandler requestCallback) { var item = (Car2GoMarker)Item; var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/bookings"; var oauth_timestamp = (DateTime?)App.GetAppSetting("car2go.oauth_token_timestamp"); if (null == oauth_timestamp) { App.ClearAppSetting("car2go.oauth_token"); App.ClearAppSetting("car2go.oauth_token_secret"); } else if (((DateTime)oauth_timestamp).AddDays(90.0).CompareTo(DateTime.UtcNow) <= 0) { App.ClearAppSetting("car2go.oauth_token"); App.ClearAppSetting("car2go.oauth_token_secret"); } var oauthToken = (string)App.GetAppSetting("car2go.oauth_token"); var oauthTokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret"); if (null == oauthToken || null == oauthTokenSecret) { HandleNotConnectedToCar2Go(null == oauth_timestamp ? "" : Strings.SettingsPageCar2GoAuthExpired); } var accountId = ""; try { accountId = ((int)App.GetAppSetting("car2go.oauth_account_id")).ToString(); } catch (NullReferenceException) { return; } var parameters = new WebParameterCollection(); parameters.Add("oauth_callback", "oob"); parameters.Add("oauth_signature_method", "HMAC-SHA1"); parameters.Add("oauth_token", oauthToken); parameters.Add("oauth_version", "1.0"); parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey); parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp()); parameters.Add("oauth_nonce", OAuthTools.GetNonce()); parameters.Add("format", "json"); parameters.Add("loc", Car2Go.City); parameters.Add("vin", item.ID); parameters.Add("account", accountId); var signatureBase = OAuthTools.ConcatenateRequestElements("POST", car2GoRequestEndpoint, parameters); var signature = OAuthTools.GetSignature( OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, oauthTokenSecret); var requestParameters = OAuthTools.NormalizeRequestParameters(parameters); var para = requestParameters + "&oauth_signature=" + signature; Helpers.Post(car2GoRequestEndpoint, para, delegate(Stream response) { if (null == response) return; var serializer = new DataContractJsonSerializer(typeof(Car2GoBookingResult)); var resultAccounts = (Car2GoBookingResult)serializer.ReadObject(response); Dispatcher.BeginInvoke(() => { var mbResult = MessageBoxResult.None; try { mbResult = 0 == resultAccounts.ReturnValue.Code ? MessageBox.Show(resultAccounts.Booking[0].Vehicle.Position.Address, resultAccounts.ReturnValue.Description, MessageBoxButton.OK) : MessageBox.Show(resultAccounts.ReturnValue.Description); } catch (Exception) { Deactivate(); } if (mbResult == MessageBoxResult.OK) { InvokeActionCompleted(); FlurryWP7SDK.Api.LogEvent("Car2GoBookingSucessfull"); } }); }); FlurryWP7SDK.Api.LogEvent("Car2GoookingStarted"); }
private void CancelCar2GoBooking() { var item = (Car2GoMarker)Item; var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/booking/" + item.BookingId; var oauthToken = (string)App.GetAppSetting("car2go.oauth_token"); var oauthTokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret"); if (null == oauthToken || null == oauthTokenSecret) { HandleNotConnectedToCar2Go(); } var accountId = ""; try { accountId = ((int)App.GetAppSetting("car2go.oauth_account_id")).ToString(); } catch (NullReferenceException) { return; } var parameters = new WebParameterCollection(); parameters.Add("oauth_callback", "oob"); parameters.Add("oauth_signature_method", "HMAC-SHA1"); parameters.Add("oauth_token", oauthToken); parameters.Add("oauth_version", "1.0"); parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey); parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp()); parameters.Add("oauth_nonce", OAuthTools.GetNonce()); parameters.Add("format", "json"); parameters.Add("account", accountId); var signatureBase = OAuthTools.ConcatenateRequestElements("DELETE", car2GoRequestEndpoint, parameters); var signature = OAuthTools.GetSignature( OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, oauthTokenSecret); var requestParameters = OAuthTools.NormalizeRequestParameters(parameters); var para = requestParameters + "&oauth_signature=" + signature; Helpers.Delete(car2GoRequestEndpoint, para, delegate(Stream args) { if (null == args) return; try { var serializer = new DataContractJsonSerializer(typeof(Car2GoCancelBookingResult)); var resultAccount = (Car2GoCancelBookingResult)serializer.ReadObject(args); Dispatcher.BeginInvoke(() => { var mbResult = MessageBoxResult.None; try { if (0 == resultAccount.ReturnValue.Code) { var message = (resultAccount.CancelBooking[0].cancelFeeExists) ? String.Format( Strings.BookingPageC2GCancelationSuccessful, resultAccount.CancelBooking[0].cancelFee, resultAccount.CancelBooking[0].cancelFeeCurrency) : String.Format( Strings.BookingPageC2GCancelationSuccessful, 0, ""); mbResult = MessageBox.Show( message, resultAccount.ReturnValue.Description, MessageBoxButton.OK); } else { mbResult = MessageBox.Show(resultAccount.ReturnValue.Description); } } catch (Exception) { Deactivate(); } if (mbResult != MessageBoxResult.OK) { return; } InvokeActionCompleted(); }); } catch (SerializationException) { InvokeActionCompleted(); } }); }