· 7 years ago · Jul 08, 2018, 08:46 AM
1const string RegionName = "eu-west-1"; //This is the regionName
2const string ServiceName = "apigateway";
3const string Algorithm = "AWS4-HMAC-SHA256";
4const string ContentType = "application/json";
5const string Host = "apigateway.eu-west-1.amazonaws.com";
6const string SignedHeaders = "content-type;host;x-amz-date";
7
8public static WebRequest RequestGet(string canonicalUri, string canonicalQueriString, string jsonString) {
9 string hashedRequestPayload = CreateRequestPayload("");
10
11 string authorization = Sign(hashedRequestPayload, "GET", canonicalUri, canonicalQueriString);
12 string requestDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + "Z";
13
14 WebRequest webRequest = WebRequest.Create("https://" + Host + canonicalUri);
15
16 webRequest.Method = "GET";
17 webRequest.ContentType = ContentType;
18 webRequest.Headers.Add("X-Amz-date", requestDate);
19 webRequest.Headers.Add("Authorization", authorization);
20 webRequest.Headers.Add("x-amz-content-sha256", hashedRequestPayload);
21
22
23 return webRequest;
24}
25
26public static WebRequest RequestPost(string canonicalUri, string canonicalQueriString, string jsonString)
27{
28 string hashedRequestPayload = CreateRequestPayload(jsonString);
29
30 string authorization = Sign(hashedRequestPayload, "POST", canonicalUri, canonicalQueriString);
31 string requestDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + "Z";
32
33 WebRequest webRequest = WebRequest.Create("https://" + Host + canonicalUri);
34
35 webRequest.Timeout = 20000;
36 webRequest.Method = "POST";
37 webRequest.ContentType = ContentType;
38 webRequest.Headers.Add("X-Amz-date", requestDate);
39 webRequest.Headers.Add("Authorization", authorization);
40 webRequest.Headers.Add("x-amz-content-sha256", hashedRequestPayload);
41 webRequest.ContentLength = jsonString.Length;
42
43 ASCIIEncoding encoding = new ASCIIEncoding();
44 byte[] data = encoding.GetBytes(jsonString);
45
46 Stream newStream = webRequest.GetRequestStream();
47 newStream.Write(data, 0, data.Length);
48
49
50 return webRequest;
51}
52
53private static string CreateRequestPayload(string jsonString) {
54 //Here should be JSON object of the model we are sending with POST request
55 //var jsonToSerialize = new { Data = String.Empty };
56
57 //We parse empty string to the serializer if we are makeing GET request
58 //string requestPayload = new JavaScriptSerializer().Serialize(jsonToSerialize);
59 string hashedRequestPayload = HexEncode(Hash(ToBytes(jsonString)));
60
61 return hashedRequestPayload;
62}
63
64private static string Sign(string hashedRequestPayload, string requestMethod, string canonicalUri, string canonicalQueryString) {
65 var currentDateTime = DateTime.UtcNow;
66 var accessKey = //Here place your app ACCESS_KEY
67 var secretKey = //Here is a place for you app SECRET_KEY
68
69 var dateStamp = currentDateTime.ToString("yyyyMMdd");
70 var requestDate = currentDateTime.ToString("yyyyMMddTHHmmss") + "Z";
71 var credentialScope = string.Format("{0}/{1}/{2}/aws4_request", dateStamp, RegionName, ServiceName);
72
73 var headers = new SortedDictionary < string, string > {
74 { "content-type", ContentType },
75 { "host", Host },
76 { "x-amz-date", requestDate }
77 };
78
79 string canonicalHeaders = string.Join("n", headers.Select(x => x.Key.ToLowerInvariant() + ":" + x.Value.Trim())) + "n";
80
81 // Task 1: Create a Canonical Request For Signature Version 4
82 string canonicalRequest = requestMethod + "n" + canonicalUri + "n" + canonicalQueryString + "n" + canonicalHeaders + "n" + SignedHeaders + "n" + hashedRequestPayload;
83 string hashedCanonicalRequest = HexEncode(Hash(ToBytes(canonicalRequest)));
84
85 // Task 2: Create a String to Sign for Signature Version 4
86 string stringToSign = Algorithm + "n" + requestDate + "n" + credentialScope + "n" + hashedCanonicalRequest;
87
88 // Task 3: Calculate the AWS Signature Version 4
89 byte[] signingKey = GetSignatureKey(secretKey, dateStamp, RegionName, ServiceName);
90 string signature = HexEncode(HmacSha256(stringToSign, signingKey));
91
92 // Task 4: Prepare a signed request
93 // Authorization: algorithm Credential=access key ID/credential scope, SignedHeadaers=SignedHeaders, Signature=signature
94
95 string authorization = string.Format("{0} Credential={1}/{2}/{3}/{4}/aws4_request, SignedHeaders={5}, Signature={6}",
96 Algorithm, accessKey, dateStamp, RegionName, ServiceName, SignedHeaders, signature);
97
98 return authorization;
99}
100
101private static byte[] GetSignatureKey(string key, string dateStamp, string regionName, string serviceName) {
102 byte[] kDate = HmacSha256(dateStamp, ToBytes("AWS4" + key));
103 byte[] kRegion = HmacSha256(regionName, kDate);
104 byte[] kService = HmacSha256(serviceName, kRegion);
105 return HmacSha256("aws4_request", kService);
106}
107
108private static byte[] ToBytes(string str) {
109 return Encoding.UTF8.GetBytes(str.ToCharArray());
110}
111
112private static string HexEncode(byte[] bytes) {
113 return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant();
114}
115
116private static byte[] Hash(byte[] bytes) {
117 return SHA256.Create().ComputeHash(bytes);
118}
119
120private static byte[] HmacSha256(string data, byte[] key) {
121 return new HMACSHA256(key).ComputeHash(ToBytes(data));
122}
123
124using(WebResponse response = webRequest.GetResponse()) {
125 StreamReader responseReader = new StreamReader(response.GetResponseStream());
126 string responseJson = responseReader.ReadToEnd();
127} catch (WebException) {
128 //Doing something when exception has been thrown
129}
130
131string payload = "{ "name" : "" + name + "", "description" : "" + description.Trim() + "", "enabled" : "True", "stageKeys" : [ ] }";
132
133WebRequest webRequest = RequestSignerAWS.RequestPost("/apikeys", "", payload);