Created
June 15, 2012 22:56
-
-
Save subnetmarco/2939141 to your computer and use it in GitHub Desktop.
C# Mashape Authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Put the "header" value into a "X-Mashape-Authorization" header before making the HTTP request | |
| // Util functions to generate a HMAC_SHA1 hash and Base64 encode a value | |
| private static String hmac_sha1(String publicKey, String privateKey) { | |
| System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); | |
| byte[] privateKeyBytes = encoding.GetBytes(privateKey); | |
| byte[] publicKeyBytes = encoding.GetBytes(publicKey); | |
| HMACSHA1 hmacsha1 = new HMACSHA1(privateKeyBytes); | |
| byte[] hash = hmacsha1.ComputeHash(publicKeyBytes); | |
| return BitConverter.ToString(hash).Replace("-","").ToLower(); | |
| } | |
| private static String EncodeTo64(string toEncode) | |
| { | |
| byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); | |
| String returnValue = System.Convert.ToBase64String(toEncodeAsBytes); | |
| return returnValue; | |
| } | |
| // Sample code using the functions above | |
| static void Main(string[] args) | |
| { | |
| String publicKey = "PUBLIC_KEY"; | |
| String hash = hmac_sha1(publicKey, "PRIVATE_KEY"); | |
| // Here we go, this is the final header value generated according to the spec: http://www.mashape.com/docs/consume/rest | |
| String header = EncodeTo64(publicKey + ":" + hash); | |
| // For example, let's use the header value above in the following GET request | |
| HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL"); | |
| // Set the header | |
| request.Headers.Add("X-Mashape-Authorization", header); | |
| HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse(); | |
| StreamReader resStream = new StreamReader(httpResponse.GetResponseStream()); | |
| // This is the response stream converted to String | |
| String stringResponse = resStream.ReadToEnd(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment