public string authorizationHeader(Dictionary <string, string> oauth) { // Convert to UTF-8 & RFC3986 (urlencode) & Sort all parameters SortedDictionary <string, string> encodedParameters = new SortedDictionary <string, string>(); foreach (KeyValuePair <string, string> entry in oauth) { encodedParameters.Add(AdskRESTful.UrlEncode(entry.Key), AdskRESTful.UrlEncode(entry.Value)); } string[] oauthArray = new string[encodedParameters.Count]; int n = 0; foreach (KeyValuePair <string, string> entry in encodedParameters) { if (entry.Key != "oauth_signature") { oauthArray[n++] = string.Format("{0}=\"{1}\"", entry.Key, entry.Value); } } oauthArray[n++] = string.Format("{0}=\"{1}\"", AdskRESTful.UrlEncode("oauth_signature"), encodedParameters[AdskRESTful.UrlEncode("oauth_signature")]); string oauthHeader = string.Join(", ", oauthArray); oauthHeader = string.Format("OAuth {0}", oauthHeader); return(oauthHeader); }
// https://dev.twitter.com/docs/auth/creating-signature // // These values need to be encoded into a single string which will be used later on. The process to build the string is very specific: // // Percent encode every key and value to be signed. // Sort the list of parameters alphabetically[1] by encoded key[2]. // For each key/value pair: // Append the encoded key to the output string // Append the '=' character to the output string // Append the encoded value to the output string // If there are more key/value pairs remaining, append a '&' character to the output string. // [1] Note: The Oauth spec says to sort lexigraphically, which is the default alphabetical sort for many libraries // [2] Note: In case of two parameters with the same encoded key, the Oauth spec says to continue sorting based on value // // To encode the HTTP method, base URL, and parameter string into a single string: // // Convert the HTTP method to uppercase // Append the '&' character // Append Percent encode the URL // Append the '&' character // Append Percent encode the parameter string public string sign(string method, Uri url, Dictionary <string, string> parameters) { // @"oauth_consumer_secret" @"oauth_token_secret" string signatureSecret = string.Format("{0}&{1}", AdskRESTful.UrlEncode(_tokens["oauth_consumer_secret"]), (_tokens.ContainsKey("oauth_token_secret") ? AdskRESTful.UrlEncode(_tokens["oauth_token_secret"]) : "") ); // Convert to UTF-8 & RFC3986 (urlencode) & Sort all parameters SortedDictionary <string, string> encodedParameters = new SortedDictionary <string, string>(); foreach (KeyValuePair <string, string> entry in parameters) { encodedParameters.Add(AdskRESTful.UrlEncode(entry.Key), AdskRESTful.UrlEncode(entry.Value)); } // Build string to be signed //Queue<string> orderedParameters =new Queue<string> () ; //foreach ( KeyValuePair<string, string> entry in encodedParameters ) // orderedParameters.Enqueue (string.Format ("{0}={1}", entry.Key, entry.Value)) ; string[] parametersArray = new string[encodedParameters.Count]; int n = 0; foreach (KeyValuePair <string, string> entry in encodedParameters) { parametersArray[n++] = string.Format("{0}={1}", entry.Key, entry.Value); } string parametersString = string.Join("&", parametersArray); string urlString = url.AbsoluteUri; // =string.Format ("{0}://{1}{2}", [url scheme], [url host], [url path]) ; string stringToSign = string.Format("{0}&{1}&{2}", AdskRESTful.UrlEncode(method.ToUpperInvariant()), AdskRESTful.UrlEncode(urlString), AdskRESTful.UrlEncode(parametersString) ); // Sign it using (HMACSHA1 hashAlgorithm = new HMACSHA1(Encoding.UTF8.GetBytes(signatureSecret))) { return(Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)))); } }
protected HttpWebRequest buildRequest(string method, string url, Dictionary <string, string> headers) { Uri rUrl; if (url.ToLower().Contains("http")) { rUrl = new Uri(url); } else { rUrl = new Uri(_url, url); } // If default headers are provided, then merge them under any explicitly provided headers for the request Dictionary <string, string> reqHeaders = new Dictionary <string, string>(); if (headers != null) { reqHeaders.Concat(headers); } // Get credential (Oauth) parameters // Get query (GET) and/or body (POST) + Credential (Oauth) parameters Dictionary <string, string> oauth = _credential.parameters; // Combine oAuth & parameters Dictionary <string, string> dict = oauth; // http://tools.ietf.org/html/rfc5849#section-3.4.1.3 << Oauth 1.0a // Include all GET and POST parameters before generating the signature // according to the RFC 5849 - The OAuth 1.0 Protocol http://tools.ietf.org/html/rfc5849#section-3.4.1 // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level, // or implement a seperate class for each OAuth version if (AlwaysSignParameters || ((_files == null || _files.Count == 0) && !AlwaysMultipart)) { dict = dict.Concat(_parameters) .GroupBy(kvp => kvp.Key, kvp => kvp.Value) .ToDictionary(g => g.Key, g => g.Last()); } if (dict.ContainsKey("realm") == true) { dict.Remove("realm"); } oauth["oauth_signature"] = _credential.sign(method, rUrl, dict); reqHeaders["Authorization"] = _credential.authorizationHeader(oauth); System.Diagnostics.Debug.WriteLine("Authorization: " + reqHeaders["Authorization"]); //reqHeaders ["User-Agent"] ="AdskRESTful/1.0" ; //reqHeaders ["Accept-Encoding"] =null/*@"gzip, deflate"*/ ; //reqHeaders ["Accept-Language"] =null ; //reqHeaders ["Accept"] =null ; //reqHeaders ["Pragma"] =null ; if (method.ToLower() == "get") { // Convert to UTF-8 & RFC3986 (urlencode) string[] encodedParameters = new string[_parameters.Count]; int n = 0; foreach (KeyValuePair <string, string> entry in _parameters) { encodedParameters[n++] = string.Format("{0}={1}", AdskRESTful.UrlEncode(entry.Key), AdskRESTful.UrlEncode(entry.Value)); } string queryString = string.Join("&", encodedParameters); string st = string.Format("{0}{1}{2}", rUrl.AbsoluteUri, rUrl.AbsoluteUri.Contains("?") ? "&" : "?", queryString ); rUrl = new Uri(st); } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(rUrl); req.KeepAlive = false; req.Method = method.ToUpperInvariant(); HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); req.CachePolicy = policy; //req.Timeout =100 ; req.UserAgent = "AdskRESTful/1.0"; foreach (KeyValuePair <string, string> entry in reqHeaders) { req.Headers.Add(entry.Key, entry.Value); } if (method.ToLower() == "post" || method.ToLower() == "put" || method.ToLower() == "delete" ) { string bodyString = ""; if (!AlwaysMultipart && (_files == null || _files.Count == 0) && _parameters.Count != 0) { // Convert to UTF-8 & RFC3986 (urlencode) if (_parameters != null) { string[] encodedParameters = new string[_parameters.Count]; int n = 0; foreach (KeyValuePair <string, string> entry in _parameters) { encodedParameters[n++] = string.Format("{0}={1}", AdskRESTful.UrlEncode(entry.Key), AdskRESTful.UrlEncode(entry.Value)); } bodyString = string.Join("&", encodedParameters); } req.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; } else { string boundaryCode = AdskRESTful.nonce().Substring(0, 12).ToLower(); string boundary = "----------------------------" + boundaryCode; req.ContentType = "multipart/form-data; boundary=" + boundary; if (_parameters != null) { foreach (KeyValuePair <string, string> entry in _parameters) { bodyString += "--" + boundary + "\r\n"; bodyString += "Content-Disposition: form-data; name=\"" + entry.Key + "\"\r\n\r\n"; bodyString += entry.Value + "\r\n"; } } if (_files != null) { int i = 0; foreach (KeyValuePair <string, string> entry in _files) { string keyName = string.Format("file[{0}]", i); //string contentType =[AdskRESTful fileMIMEType:key] ; string contentType = "image/jpeg"; bodyString += "--" + boundary + "\r\n"; bodyString += "Content-Disposition: form-data; name=\"" + keyName + "\"; filename=\"" + AdskRESTful.UrlEncode(entry.Key) + "\"\r\n\r\n"; bodyString += "Content-Type: " + contentType + "\r\n\r\n"; bodyString += entry.Value; bodyString += "\r\n"; i++; } } bodyString += "--" + boundary + "--\r\n"; } byte[] byte1 = Encoding.UTF8.GetBytes(bodyString); //req.ContentLength =byte1.Length ; try { System.IO.Stream body = req.GetRequestStream(); body.Write(byte1, 0, byte1.Length); body.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } return(req); }