TankorSmash

OAuth1a.cs

Nov 12th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.66 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using HtmlAgilityPack;
  8. using System.Web;
  9. namespace NetflixAPI
  10. {
  11.     static class OAuth1a
  12.     {
  13.         //gameplan:
  14.         // target URL
  15.         // Netflix params: Title, offset, limit
  16.         // Oauth params: consumer_key, nonce, timestamp, signature_method
  17.         //
  18.         // and then the signature after, which is based on the above encoded
  19.         //
  20.         // HMAC outputs 20 chars, turn that to b64 then encode that
  21.         //
  22.         // NEed to encode certain chars AND make sure to encode it befre I pass
  23.         // it to the MHA or whatever
  24.  
  25.         public static void Start()
  26.         {
  27.             string VERB = "GET";
  28.             string URL = "http://api-public.netflix.com/catalog/titles";
  29.  
  30.                 //Not going to change
  31.    
  32.             string consumer_key = "u7r68et24v6rd5r9u828qvte";
  33.             string consumer_secret = "uWdp2AXnnu";
  34.             string oauth_signature_method = "HMAC-SHA1";
  35.             string oauth_version = "1.0";
  36.  
  37.                 //dynamic values
  38.             string oauth_timestamp = GenerateTimeStamp();
  39.             string oauth_nonce = GenerateTimeStamp();
  40.             string oauth_signature = GenerateSignature(VERB, URL,
  41.                                                        consumer_key,
  42.                                                        consumer_secret,
  43.                                                        oauth_timestamp,
  44.                                                        oauth_nonce,
  45.                                                        oauth_signature_method,
  46.                                                        new KeyValuePair
  47.                                                            <string, string>(
  48.                                                            "term", "liar"),
  49.                                                        new KeyValuePair
  50.                                                            <string, string>(
  51.                                                            "start_index", "0"),
  52.                                                        new KeyValuePair
  53.                                                            <string, string>(
  54.                                                            "max_results", "25"));
  55.             Console.WriteLine(oauth_signature);
  56.  
  57.             //Need to send the request now, will have to learn about headers, probably.
  58.             string authorizationHeaderParams = String.Empty;
  59.             authorizationHeaderParams += "OAuth ";
  60.             authorizationHeaderParams += "oauth_nonce=" + "\"" +
  61.                 Uri.EscapeDataString(oauth_nonce) + "\",";
  62.  
  63.             authorizationHeaderParams +=
  64.                 "oauth_signature_method=" + "\"" +
  65.                 Uri.EscapeDataString(oauth_signature_method) +
  66.                 "\",";
  67.  
  68.             authorizationHeaderParams += "oauth_timestamp=" + "\"" +
  69.                 Uri.EscapeDataString(oauth_timestamp) + "\",";
  70.  
  71.             authorizationHeaderParams += "oauth_consumer_key="
  72.                 + "\"" + Uri.EscapeDataString(
  73.                 consumer_key) + "\",";
  74.  
  75.             //authorizationHeaderParams += "oauth_token=" + "\"" +
  76.             //    Uri.EscapeDataString(oauth_token) + "\",";
  77.  
  78.             authorizationHeaderParams += "oauth_signature=" + "\""
  79.                 + Uri.EscapeDataString(oauth_signature) + "\",";
  80.  
  81.             authorizationHeaderParams += "oauth_version=" + "\"" +
  82.                 Uri.EscapeDataString(oauth_version) + "\"";
  83.  
  84.  
  85.             //needs the baseurl, then add in all the params, followed by the
  86.             //signature
  87.  
  88.             string toSend =
  89.                 String.Format("{0}?max_results={2}&oauth_consumer_key={3}&oauth_nonce={4}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={5}&oauth_version=1.0&start_index=0&term={1}&oauth_signature={6}",
  90.                         URL, "liar", "25", consumer_key, oauth_nonce,
  91.                         oauth_timestamp, oauth_signature);
  92.  
  93.             //get the URL to send, now we need to create ethe request
  94.             //WebRequest web = WebRequest.Create(toSend);
  95.             HttpWebRequest web = (HttpWebRequest)WebRequest.Create(toSend);
  96.             web.KeepAlive = false;
  97.             //add headers, except when I do, I get 403 instead of 401s statuses
  98.             //web.Headers.Add( "Authorization", authorizationHeaderParams);
  99.             Stream objStream;
  100.             objStream = web.GetResponse().GetResponseStream();
  101.             StreamReader objReader = new StreamReader(objStream);
  102.  
  103.             string sLine = "";
  104.             int i = 0;
  105.  
  106.             while (sLine!=null)
  107.             {
  108.                 i++;
  109.                 sLine = objReader.ReadLine();
  110.                 if (sLine!=null)
  111.                     Console.WriteLine("{0}:{1}",i,sLine);
  112.             }
  113.             Console.ReadLine();
  114.            
  115.  
  116.             Console.WriteLine("Done!");
  117.         }
  118.  
  119.         public static string GenerateTimeStamp()
  120.         {
  121.             double time = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
  122.             return Convert.ToInt32(time).ToString();
  123.         }
  124.  
  125.         public static string GenerateNonce()
  126.         {
  127.             return Guid.NewGuid().ToString();
  128.         }
  129.  
  130.         public static string GenerateSignature(string HttpMethod, string url,
  131.                 string consumer_key, string consumer_secret, string
  132.                 oauth_timestamp, string oauth_nonce, string
  133.                 oauth_signature_method= "HMACSHA1", params KeyValuePair<string,
  134.                 string>[] parameters)
  135.         {
  136.             //so this needs an encoded base string, which'll be
  137.             //METHOD&URL&PARAMS
  138.             //then I pass it to the HMAC-SHA1 which spits out a 20char, which'll
  139.             //be encoded and used as sig param on the unencoded basestring
  140.  
  141.             //create BASESTRING where we already know the METHOD and URL, so we
  142.             //need to grab all the params
  143.             // string enc_params = GenerateEncodedParameterString(consumer_key
  144.             // :"consumer_key" ,
  145.             //         oauth_signature_method :"oauth_signature_method" ,
  146.             //         oauth_version "oauth_version" , oauth_timestamp
  147.             //         :"oauth_timestamp" ,
  148.             //         oauth_nonce : "oauth_nonce" , parameters);
  149.  
  150.  
  151.             //This is a set of params that need to be passed to the paramString method, but the
  152.             // method is expecting an array of KVPs so I need to make an array
  153.             // from the default OAuth args and then add the custom params, like
  154.             // Term and stuff later.
  155.             KeyValuePair<string, string>[] qwe =
  156.                 {
  157.                     new KeyValuePair<string, string>("oauth_consumer_key", consumer_key),
  158.                     new KeyValuePair<string, string>("oauth_signature_method", oauth_signature_method),
  159.                     new KeyValuePair<string, string>("oauth_version", "1.0"),
  160.                     new KeyValuePair<string, string>("oauth_timestamp", oauth_timestamp),
  161.                     new KeyValuePair<string, string>("oauth_nonce", oauth_nonce)
  162.                 };
  163.  
  164.             //Turn the array to a list so you can addrange, then back to an array
  165.             // for the sake of the method which requires it.
  166.             var poop = parameters.ToList();
  167.                 poop.AddRange(qwe);
  168.             var a_listed_poop = poop.ToArray();
  169.             string enc_params = GenerateEncodedParameterString(a_listed_poop);
  170.            
  171.             //Now we've got the encoded param set, we need to encode the uri and prepend the httpmethod.
  172.  
  173.  
  174.             //TODO: fix the hardcoded key
  175.             string signString = consumer_key + "&";
  176.  
  177.             //need this basestring to combine with the signString to make the
  178.             //signature, once we add it to the SHA1 or whatever
  179.             string encodedBaseString = GenerateEncodedBaseString(HttpMethod, url, enc_params);
  180.  
  181.             string encoded_signature = Sign(encodedBaseString, signString);
  182.  
  183.             //return encoded_signature;
  184.             return HttpUtility.UrlEncode(encoded_signature);
  185.         }
  186.  
  187.         public static string GenerateEncodedParameterString( params KeyValuePair<string,string>[] parameters)
  188.         {
  189.             var q = from entry in parameters
  190.                 let encodedkey = HttpUtility.UrlEncode(entry.Key)
  191.                 let encodedValue = HttpUtility.UrlEncode(entry.Value)
  192.                 let encodedEntry = encodedkey + "=" + encodedValue
  193.                 orderby encodedEntry
  194.                 select encodedEntry;
  195.             var a = q.ToArray();
  196.             var result = string.Join("&", a);
  197.             return result;
  198.         }
  199.  
  200.         public static string GenerateEncodedBaseString( string HttpMethod, string baseURI, string paramString)
  201.         {
  202.             //returns method&url&params encoded
  203.              return HttpMethod.ToUpper() + "&" + HttpUtility.UrlEncode(baseURI) + "&" + HttpUtility.UrlEncode(paramString);
  204.         }
  205.  
  206.         public static string Sign(string signatureBaseString, string signingKey)
  207.         {
  208.             var keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
  209.             using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes)) {
  210.                 byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
  211.                 var stream = new MemoryStream(byteArray);
  212.                 var signedValue = myhmacsha1.ComputeHash(stream);
  213.                 var result = Convert.ToBase64String(signedValue, Base64FormattingOptions.None);
  214.                 return result;
  215.             }
  216.         }
  217.  
  218.  
  219.     }
  220. }
Add Comment
Please, Sign In to add comment