Api Gateway invokation

0

Hello AWS Support,

I am currently implementing a virtual waiting room using the "Getting Started" template and am encountering an issue when attempting to invoke the increment_serving_counter API endpoint from my .NET application. The API invocation consistently fails

Here is the relevant code snippet for the API call:

public static async Task<bool> IncrementServingCounterAsync()
        {
            string awsKeyId = "";
            string awsKeySecret = "";
            string region = "";
            string service = "execute-api";

            var endpoint = "endPoint/increment_serving_counter";

            var requestBody = new
            {
                event_id = "myEventId",
                increment_by = 1
            };

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, endpoint)
            {
                Content = new StringContent(
                    Newtonsoft.Json.JsonConvert.SerializeObject(requestBody),
                    Encoding.UTF8,
                    "application/json"
                )
            };

            // Sign the request
            SignRequest(requestMessage, awsKeyId, awsKeySecret, region, service);

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.SendAsync(requestMessage);
                return response.IsSuccessStatusCode;
            }
        }

        private static void SignRequest(HttpRequestMessage request, string accessKey, string secretKey, string region, string service)
        {
            // Implement AWS Signature Version 4 signing here
            var algorithm = "AWS4-HMAC-SHA256";
            var amzDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + "Z";
            var dateStamp = DateTime.UtcNow.ToString("yyyyMMdd");

            // Construct canonical request
            var canonicalUri = request.RequestUri.AbsolutePath;
            var canonicalQueryString = string.Empty;
            var canonicalHeaders = $"host:{request.RequestUri.Host}\n";
            var signedHeaders = "host";
            var payloadHash = ComputeSha256Hash(request.Content.ReadAsStringAsync().Result);
            var canonicalRequest = $"{request.Method}\n{canonicalUri}\n{canonicalQueryString}\n{canonicalHeaders}\n{signedHeaders}\n{payloadHash}";

            // Create the string to sign
            var credentialScope = $"{dateStamp}/{region}/{service}/aws4_request";
            var stringToSign = $"{algorithm}\n{amzDate}\n{credentialScope}\n{ComputeSha256Hash(canonicalRequest)}";

            // Calculate the signature
            var signingKey = GetSignatureKey(secretKey, dateStamp, region, service);
            var signature = ComputeHmacSha256(signingKey, stringToSign);

            // Add authorization header to the request
            var authorizationHeader = $"{algorithm} Credential={accessKey}/{credentialScope}, SignedHeaders={signedHeaders}, Signature={signature}";
            request.Headers.Authorization = new AuthenticationHeaderValue("AWS4-HMAC-SHA256", authorizationHeader);
            request.Headers.Add("x-amz-date", amzDate);
        }

        private static string ComputeSha256Hash(string data)
        {
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }

        private static byte[] ComputeHmacSha256(byte[] key, string data)
        {
            using (var hmac = new HMACSHA256(key))
            {
                return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
            }
        }

        private static byte[] GetSignatureKey(string key, string dateStamp, string region, string service)
        {
            var kDate = ComputeHmacSha256(Encoding.UTF8.GetBytes("AWS4" + key), dateStamp);
            var kRegion = ComputeHmacSha256(kDate, region);
            var kService = ComputeHmacSha256(kRegion, service);
            var kSigning = ComputeHmacSha256(kService, "aws4_request");
            return kSigning;
        }

I have verified that the endpoint URL and AWS credentials are correct.

Thank you for your assistance.

Best regards,

Nick Pnevmatikos

1 Answer
0

Hi Nick. To resolve the issue with invoking the increment_serving_counter API, ensure that the AWS Signature Version 4 signing process is correctly implemented, as errors in this step often cause API requests to fail. Additionally, verify that the endpoint URL and AWS credentials are accurate. Enabling detailed logging in your .NET application could help identify where the request is failing. I hope this helps.

profile picture
EXPERT
answered 2 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions