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 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 }); }
public void Can_generate_timestamp() { var timestamp = OAuthTools.GetTimestamp(); Assert.IsNotNull(timestamp); Assert.IsTrue(timestamp.Length == 10, "What century is this?"); Console.WriteLine(timestamp); }
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 GetTimeStamp_Time_Before_Epoch_Is_Accurate() { DateTime earlyDateTime = new DateTime(1900, 1, 1); string unixTime = OAuthTools.GetTimestamp(earlyDateTime); Assert.NotNull(unixTime); Assert.NotEmpty(unixTime); Assert.Equal((earlyDateTime - new DateTime(1970, 1, 1)).TotalSeconds, Convert.ToInt64(unixTime)); }
public void GetTimeStamp_Calculates_Seconds_From_Epoch() { int secondsFromEpoch = 1000; DateTime dateTimeFromEpoch = new DateTime(1970, 1, 1).AddSeconds(secondsFromEpoch); string unixTime = OAuthTools.GetTimestamp(dateTimeFromEpoch); Assert.NotNull(unixTime); Assert.NotEmpty(unixTime); Assert.Equal(secondsFromEpoch, Convert.ToInt32(unixTime)); }
/// <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 }); }
private void LoadCities() { var wc = new WebClient(); var callUri = "https://www.car2go.com/api/v2.1/locations?&format=json&oauth_consumer_key=" + consumerkey + "×tamp=" + OAuthTools.GetTimestamp(); wc.OpenReadCompleted += delegate(object o, OpenReadCompletedEventArgs e) { var cities = new List <Car2GoLocation>(); try { var serializer = new DataContractJsonSerializer(typeof(Car2GoLocations)); cities = new List <Car2GoLocation>(((Car2GoLocations)serializer.ReadObject(e.Result)).location); } catch (WebException) { } catch (NullReferenceException) { } cities.Insert(0, new Car2GoLocation { locationName = "Autodetect", locationId = 0, }); cities.Insert(0, null); Cities = cities; }; wc.OpenReadAsync(new Uri(callUri)); }
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 LoadMulticityCars() { if (null == position) { return; } try { if (false == (bool)IsolatedStorageSettings.ApplicationSettings["settings_show_multicity_cars"]) { Markers = new List <MulticityMarker>(); TriggerUpdated("cars"); return; } } catch (KeyNotFoundException) { } var wc = new WebClient(); var cultureInfo = new CultureInfo("en-US"); var lat = position.Location.Latitude.ToString(cultureInfo.NumberFormat); var lng = position.Location.Longitude.ToString(cultureInfo.NumberFormat); var callUri = "https://kunden.multicity-carsharing.de/kundenbuchung/hal2ajax_process.php?zoom=10&lng1=&lat1=&lng2=&lat2=&stadtCache=&mapstation_id=&mapstadt_id=&verwaltungfirma=¢erLng=" + lng + "¢erLat=" + lat + "&searchmode=buchanfrage&with_staedte=false&buchungsanfrage=J&lat=" + lat + "&lng=" + lng + "&instant_access=J&open_end=J&objectname=multicitymarker&clustername=multicitycluster&ignore_virtual_stations=J&before=null&after=null&ajxmod=hal2map&callee=getMarker&_=" + OAuthTools.GetTimestamp(); wc.OpenReadCompleted += OnMulticityCarsOpenReadCompleted; wc.OpenReadAsync(new Uri(callUri)); }
/// <summary> /// Signs the specified URL with HMAC-SHA1 using the private key. /// </summary> /// <param name="url">The URL.</param> /// <returns>Signed URL.</returns> private string SignURL(string url) { var guid = Guid.NewGuid(); return(url + "&appid=android2&device=" + guid + "&locale=en_US×tamp=" + OAuthTools.GetTimestamp() + "&sig=and2-" + OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, url + "&appid=android2&device=" + guid + "&locale=en_US", Key)); }
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 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); } }
private void LoadCars() { if (null == position) { return; } try { if (false == (bool)IsolatedStorageSettings.ApplicationSettings["settings_show_car2go_cars"]) { Markers = new List <Car2GoMarker>(); if (null != Updated) { Updated(this, null); } return; } } catch (KeyNotFoundException) { } var wc = new WebClient(); var callUri = "https://www.car2go.com/api/v2.1/vehicles?loc=" + City + "&format=json&oauth_consumer_key=" + consumerkey + "×tamp=" + OAuthTools.GetTimestamp(); wc.OpenReadCompleted += OnCar2GoCarsOpenReadCompleted; wc.OpenReadAsync(new Uri(callUri)); }
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(); } }); }
private void LoadDriveNowCars() { if (null == position) { return; } try { if (false == (bool)IsolatedStorageSettings.ApplicationSettings["settings_show_drivenow_cars"]) { Markers = new List <DriveNowMarker>(); if (null != Updated) { Updated(this, null); } return; } } catch (KeyNotFoundException) { } var wc = new WebClient(); //var callUri = "https://www.drive-now.com/php/metropolis/json.vehicle_filter?tenant=germany&language=de_DE&L=0&url=%2Fphp%2Fmetropolis%2Fcity_berlin&redirect_flag=1"; var callUri = "https://m.drive-now.com/php/metropolis/json.vehicle_filter?timestamp=" + OAuthTools.GetTimestamp(); wc.OpenReadCompleted += OnDriveNowCarsOpenReadCompleted; wc.OpenReadAsync(new Uri(callUri)); }