public
Created

C# Mashape Authentication

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
// 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();
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.