/// <summary> /// Determines if an incoming request is authentic. /// </summary> /// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param> /// <param name="shopifySecretKey">Your app's secret key.</param> /// <returns>A boolean indicating whether the request is authentic or not.</returns> public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey) { string signature = querystring.Get("signature"); //Convert the querystring to a dictionary, which lets us query it with LINQ IDictionary<string, string> parameters = querystring .Cast<string>() .Select(s => new { Key = s, Value = querystring[s] }) .ToDictionary(d => d.Key, d => d.Value); //To calculate signature, order all querystring parameters by alphabetical (exclude the signature itself), and append it to the secret key. string calculatedSignature = shopifySecretKey + string.Join(null, parameters .Where(x => x.Key != "signature") .OrderBy(x => x.Key) .Select(x => string.Format("{0}={1}", x.Key, x.Value))); //Convert calculated signature to bytes Byte[] sigBytes = Encoding.UTF8.GetBytes(calculatedSignature); //Runt hose bytes through an MD5 hash using (MD5 md5 = MD5.Create()) { sigBytes = md5.ComputeHash(sigBytes); } //Convert bytes back to string, replacing dashes, to get the final signature. calculatedSignature = BitConverter.ToString(sigBytes).Replace("-", ""); //Request is valid if the calculated signature matches the signature from the querystring. return calculatedSignature.ToUpper() == signature.ToUpper(); }
public FlowRequest Create(NameValueCollection nameValueCollection) { Dictionary<string, string> dictionary = nameValueCollection.Cast<string>() .Select(s => new {Key = s, Value = nameValueCollection[s]}) .ToDictionary(p => p.Key, p => p.Value); return Create(dictionary); }
public QueryBuilder(NameValueCollection collection) { Query = collection == null ? string.Empty : string.Join(AMPERSAND, collection.Cast<string>() .Where(key => !string.IsNullOrEmpty(key)) .Select(key => encode(key)+ EQUALS + encode(collection[key]))); }
public static IEnumerable <KeyValuePair <string, string> > ToPairs(this NameValueCollection collection) { if (collection == null) { throw new ArgumentNullException("collection"); } return(collection.Cast <string>().Select(key => new KeyValuePair <string, string>(key, collection[key]))); }
/// <summary> /// 将NameValueCollection键值集合按字母a到z的顺便数组url字符串 /// </summary> /// <param name="nv"></param> /// <returns></returns> public static string GetStrAzNv(System.Collections.Specialized.NameValueCollection nv) { string str = string.Empty; if (nv.Count > 0) { Dictionary <string, string> list = nv.Cast <string>().ToDictionary(x => x, x => nv[x]); str = AzGetStr(list); } return(str); }
public void Parse(NameValueCollection nameValueCollection) { if (nameValueCollection != null) { _settings = nameValueCollection.Cast<NameObjectCollectionBase>().Select(nvc => new Setting { Key =nvc. }); return _settings; } }
public static byte[] SerializeRequestToBytes(this HttpRequestBase request, string renameHost) { if (string.IsNullOrEmpty(renameHost)) return SerializeRequestToBytes(request); return SerializeRequestToBytes(request, r => { var requestHeaders = new NameValueCollection(r.Headers); requestHeaders["Host"] = renameHost; var headers = requestHeaders.Cast<string>() .Select(h => string.Format("{0}: {1}", h, r.Headers[h])) .ToArray(); return string.Join(Environment.NewLine, headers); }); }
public static string ConstructStringToSign(string httpMethod, NameValueCollection headers, string pathAndQuery) { StringBuilder stringToSign = new StringBuilder(); var httpVerb = httpMethod.Trim() + "\n"; var csodHeaders = headers.Cast<string>().Where(w => w.StartsWith("x-csod-")) .Where(w => w != "x-csod-signature") .Distinct() .OrderBy(s => s) .Aggregate(string.Empty, (a, l) => a + l.ToLower().Trim() + ":" + headers[l].Trim() + "\n"); stringToSign.Append(httpVerb); stringToSign.Append(csodHeaders); stringToSign.Append(pathAndQuery); return stringToSign.ToString(); }
/// <summary> /// Determines if an incoming request is authentic. /// </summary> /// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param> /// <param name="shopifySecretKey">Your app's secret key.</param> /// <returns>A boolean indicating whether the request is authentic or not.</returns> public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey) { string hmac = querystring.Get("hmac"); if (string.IsNullOrEmpty(hmac)) { return false; } // To calculate HMAC signature: // 1. Cast querystring to KVP pairs. // 2. Remove `signature` and `hmac` keys. // 3. Replace & with %26, % with %25 in keys and values. // 4. Replace = with %3D in keys only. // 5. Join each key and value with = (key=value). // 6. Sorty kvps alphabetically. // 7. Join kvps together with & (key=value&key=value&key=value). // 8. Compute the kvps with an HMAC-SHA256 using the secret key. // 9. Request is authentic if the computed string equals the `hash` in query string. // Reference: https://docs.shopify.com/api/guides/authentication/oauth#making-authenticated-requests Func<string, bool, string> replaceChars = (string s, bool isKey) => { //Important: Replace % before replacing &. Else second replace will replace those %25s. string output = (s?.Replace("%", "%25").Replace("&", "%26")) ?? ""; if (isKey) { output = output.Replace("=", "%3D"); } return output; }; var kvps = querystring.Cast<string>() .Select(s => new { Key = replaceChars(s, true), Value = replaceChars(querystring[s], false) }) .Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac") .OrderBy(kvp => kvp.Key) .Select(kvp => $"{kvp.Key}={kvp.Value}"); var hmacHasher = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey)); var hash = hmacHasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("&", kvps))); //Convert bytes back to string, replacing dashes, to get the final signature. var calculatedSignature = BitConverter.ToString(hash).Replace("-", ""); //Request is valid if the calculated signature matches the signature from the querystring. return calculatedSignature.ToUpper() == hmac.ToUpper(); }
/// <summary> /// Determines if an incoming proxy page request is authentic. Conceptually similar to <see cref="IsAuthenticRequest(NameValueCollection, string)"/>, /// except that proxy requests use HMACSHA256 rather than MD5. /// </summary> /// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param> /// <param name="shopifySecretKey">Your app's secret key.</param> /// <returns>A boolean indicating whether the request is authentic or not.</returns> public static bool IsAuthenticProxyRequest(NameValueCollection querystring, string shopifySecretKey) { string signature = querystring.Get("signature"); // To calculate signature, order all querystring parameters by alphabetical (exclude the // signature itself). Then, hash it with the secret key. var parameters = querystring .Cast<string>() .Select(s => new { Key = s, Value = querystring[s] }) .ToDictionary(d => d.Key, d => d.Value) .Where(x => x.Key != "signature") .OrderBy(x => x.Key) .Select(x => string.Format("{0}={1}", x.Key, x.Value)); var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(string.Join(null, parameters))); //Convert bytes back to string, replacing dashes, to get the final signature. var calculatedSignature = BitConverter.ToString(hash).Replace("-", ""); //Request is valid if the calculated signature matches the signature from the querystring. return calculatedSignature.ToUpper() == signature.ToUpper(); }
private static string Singularise(string input, NameValueCollection singularisationRules) { var singularisationRule = singularisationRules .Cast<string>() .Where(rule => Regex.IsMatch(input, rule, RegexOptions.IgnoreCase)) .FirstOrDefault(); if (singularisationRule != null) { return Regex.Replace(input, singularisationRule, singularisationRules[singularisationRule], RegexOptions.IgnoreCase); } return null; }
/// <summary> /// Determines if an incoming proxy page request is authentic. Conceptually similar to <see cref="IsAuthenticRequest(NameValueCollection, string)"/>, /// except that proxy requests use HMACSHA256 rather than MD5. /// </summary> /// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param> /// <param name="shopifySecretKey">Your app's secret key.</param> /// <returns>A boolean indicating whether the request is authentic or not.</returns> public static bool IsAuthenticProxyRequest(NameValueCollection querystring, string shopifySecretKey) { string signature = querystring.Get("signature"); if (string.IsNullOrEmpty(signature)) { return false; } // To calculate signature, order all querystring parameters by alphabetical (exclude the // signature itself). Then, hash it with the secret key. Func<string, bool, string> replaceChars = (string s, bool isKey) => { //Important: Replace % before replacing &. Else second replace will replace those %25s. string output = (s?.Replace("%", "%25").Replace("&", "%26")) ?? ""; if (isKey) { output = output.Replace("=", "%3D"); } return output; }; var kvps = querystring.Cast<string>() .Select(s => new { Key = replaceChars(s, true), Value = replaceChars(querystring[s], false) }) .Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac") .OrderBy(kvp => kvp.Key) .Select(kvp => $"{kvp.Key}={kvp.Value}"); var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(string.Join(null, kvps))); //Convert bytes back to string, replacing dashes, to get the final signature. var calculatedSignature = BitConverter.ToString(hash).Replace("-", ""); //Request is valid if the calculated signature matches the signature from the querystring. return calculatedSignature.ToUpper() == signature.ToUpper(); }
public static string Dump(NameValueCollection nameValueCollection) { return nameValueCollection.Cast<string>().ToString(key => key + ": " + nameValueCollection[key], "\r\n"); }
public static String ConstructQueryString(NameValueCollection parameters, string separator = "&") { return String.Join(separator, parameters.Cast<string>().Select(parameter => parameter + "=" + parameters[parameter]) ); }
private String GetSignatureHash(NameValueCollection col) { return GetSignatureHash(col.Cast<string>().Select(e => col[e])); }
private static Dictionary<string, string> BuildDictionaryFromNameValueCollection( NameValueCollection nameValueCollection ) { return nameValueCollection.Cast<string>().Select( s => new { Key = s, Value = nameValueCollection[s] } ).ToDictionary( p => p.Key, p => p.Value ); }
protected void Page_Load(object sender, EventArgs e) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((a, b, c, d) => true); // Create a request using a URL that can receive a post. //WebRequest request = WebRequest.Create("https://localhost:44300/login"); //RESTSHARP! var restclient = new RestClient("https://localhost:44300"); restclient.Authenticator = new SimpleAuthenticator("userName", "mathieu", "password", "asd"); var restrequest = new RestRequest("/login", Method.POST); restrequest.AddHeader("Accept", "*/*"); var restresponse = restclient.Execute(restrequest); var responseCookies = restresponse.Cookies; restclient.AddDefaultHeader("Client", "RichClient"); restclient.Authenticator = null; var secureRequest = new RestRequest("/secure"); //secureRequest.AddCookie(responseCookies[0].Name, responseCookies[0].Value); var secureResponse = restclient.Execute(secureRequest); CookieContainer cookieJar = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://localhost:44300/login"); request.CookieContainer = cookieJar; request.Headers.Add("Client", "RichClient"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. NameValueCollection nvc = new NameValueCollection(); nvc.Add("userName", "mathieu"); nvc.Add("password", "abc"); var values = nvc.Cast<string>().Select(x => string.Format("{0}={1}", x, HttpUtility.UrlEncode(nvc[x]))).ToArray(); var postValues = string.Join("&", values); byte[] byteArray = Encoding.UTF8.GetBytes(postValues); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. //WebResponse response = request.GetResponse(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); int cookieCount = cookieJar.Count; var cookies = cookieJar.GetCookies(new Uri("http://localhost")); var cookieValue = cookies.Cast<Cookie>().First().Value; // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); OtherRequest(cookieJar); }
protected Exception CreateErrorResult(NameValueCollection errors) { return new Exception(errors.Cast<string>().Select(e => errors[e]).ToString()); }
private NameValueCollection Submit(NameValueCollection values,string requestUrl) { string data = String.Join("&", values.Cast<string>() .Select(key => String.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key])))); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); request.Method = "POST"; request.ContentLength = data.Length; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(data); } using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream())) { return HttpUtility.ParseQueryString(reader.ReadToEnd()); } }
private string GetUrl(NameValueCollection values, string requestUrl) { string data = String.Join("&", values.Cast<string>() .Select(key => String.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key])))); return String.Format("{0}/{1}", requestUrl, data); }
public IDictionary<string, object> ToDictionary(NameValueCollection source) { return source.Cast<string>() .Select(s => new { Key = s, Value = source[s] }) .ToDictionary(p => p.Key, p => p.Value as object); }
protected string NormalizeRequestParams(NameValueCollection requestParams) { var values = requestParams .Cast<string>() .Select( key => new KeyValuePair<string, string>(key, requestParams[key]) ); return string.Join("&", values.OrderBy(value => value.Key) .Select(value => string.Format("{0}={1}", value.Key, (value.Value ?? ""))) .ToArray() ); }