//This returns an XML string from the SQS queue that contains the 10 most recent messages.
        public static string GetSQSMessages()
        {
            string region = config["Region"];
            // Construct a virtual hosted style address with the bucket name part of the host address,
            // placing the region into the url if we're not using us-east-1.
            var regionUrlPart = string.Format("-{0}", region);
            //This is our QA fifo queue, replace it with your queue's url
            var endpointUri       = BaseUrl + config["AccountId"] + "/" + config["QueueName"];
            var requestParameters = "Action=ReceiveMessage&MaxNumberOfMessages=" + MessagesToReceieve;
            var uri     = new Uri(endpointUri + "?" + requestParameters);
            var headers = new Dictionary <string, string>()
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 }
//                {"content-type", "text/plain"}
            };
            //Use the AWS4 signer to generate the signer and sign the request
            var signer = new AWS4SignerForAuthorizationHeader()
            {
                EndpointUri = uri,
                HttpMethod  = "GET",
                Service     = "sqs",
                Region      = region
            };

            var authorization = signer.ComputeSignature(headers, requestParameters, AWS4SignerBase.EMPTY_BODY_SHA256,
                                                        config["AccessKey"], config["SecretKey"]);

            headers.Add("Authorization", authorization);

            string response = HttpHelpers.InvokeHttpRequest(uri, "GET", headers, null);

            //Console.WriteLine(response);
            return(response);
        }
Beispiel #2
0
        public static string GenerateGetRequestMethod(string entityType, string entityId)
        {
            //Generates a JSON object from the session token JSON string
            JObject credentials = JObject.Parse(GetSessionToken().Result);

            var endpointUri = BaseConnectionString + entityType + "/" + entityId;
            var uri         = new Uri(endpointUri);
            var headers     = new Dictionary <string, string>()
            {
                { "content-type", "application/x-www-form-urlencoded" },
                { "x-amz-security-token", credentials.GetValue("sessionToken").ToString() },
                { "x-api-key", ConfigSetup.ApiKey }
            };

            //Use the AWS4 signer to generate the signer and sign the request
            var signer = new AWS4SignerForAuthorizationHeader()
            {
                EndpointUri = uri,
                HttpMethod  = "GET",
                Service     = "execute-api",
                Region      = Region
            };
            //Uses the generated accessKey and secretKey from GenerateSessionToken(), NOT FROM CONFIG
            var authorization = signer.ComputeSignature(headers, "", AWS4SignerBase.EMPTY_BODY_SHA256,
                                                        credentials.GetValue("accessKey").ToString(), credentials.GetValue("secretKey").ToString());

            Console.WriteLine(authorization);
            //Add the signed authorization to headers
            Console.WriteLine("AUTHORIZATION: " + authorization);
            headers.Add("Authorization", authorization);
            string response = HttpHelpers.InvokeHttpRequest(uri, "GET", headers, null);

            //Console.WriteLine(response);
            return(response);
        }
Beispiel #3
0
        /// <summary>
        /// Request the content of an object from the specified bucket using virtual hosted-style
        /// object addressing.
        /// </summary>
        public static void Run(string objectKey, string email, string awsAccessKey, string awsSecretKey)
        {
            Console.WriteLine("GetConfidential");

            var endpointUri = $"https://localhost:44397/{objectKey}/{email}";

            var uri = new Uri(endpointUri);

            // for a simple GET, we have no body so supply the precomputed 'empty' hash
            var headers = new Dictionary <string, string>
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 },
                { "content-type", "text/plain" }
            };

            var signer = new AWS4SignerForAuthorizationHeader
            {
                EndpointUri = uri,
                HttpMethod  = "GET",
                Service     = "",
                Region      = ""
            };

            var authorization = signer.ComputeSignature(headers,
                                                        "",   // no query parameters
                                                        AWS4SignerBase.EMPTY_BODY_SHA256,
                                                        awsAccessKey,
                                                        awsSecretKey);

            // place the computed signature into a formatted 'Authorization' header
            // and call S3
            headers.Add("Authorization", authorization);

            HttpHelpers.InvokeHttpRequest(uri, "GET", headers, null);
        }
Beispiel #4
0
        /// <summary>
        /// Uploads content to an Amazon S3 object in a single call using Signature V4 authorization.
        /// </summary>
        public static void Run(string filePath, Stream objectToSave, RegionEndpoint region, string bucketName, string accessKey, string secretKey)
        {
            var endpointUri = $"https://{bucketName}.s3-{region.SystemName}.amazonaws.com/{filePath}";
            var uri         = new Uri(endpointUri);

            var contentHash = AWS4SignerBase.CanonicalRequestHashAlgorithm.ComputeHash(objectToSave);

            objectToSave.Position = 0;
            var contentHashString = AWS4SignerBase.ToHexString(contentHash, true);

            var headers = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, contentHashString },
                { AWS4SignerBase.X_Amz_Expires, TimeSpan.FromMinutes(5).TotalSeconds.ToString() },
                { AWS4SignerBase.X_Amz_Acl, "public-read" },
                { "content-length", objectToSave.Length.ToString() },
                { "content-type", "image/*" },
            };

            var signer = new AWS4SignerForAuthorizationHeader
            {
                EndpointUri = uri,
                HttpMethod  = WebRequestMethods.Http.Put,
                Service     = "s3",
                Region      = region.SystemName
            };

            var authorization = signer.ComputeSignature(headers, "", contentHashString, accessKey, secretKey);

            headers.Add("Authorization", authorization);
            HttpHelpers.InvokeHttpRequest(uri, WebRequestMethods.Http.Put, headers, objectToSave);
        }
Beispiel #5
0
        private static Dictionary <string, string> BuildHeaders(Uri uri, string payload)
        {
            byte[] contentHash       = AWS4SignerBase.CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(payload));
            string contentHashString = AWS4SignerBase.ToHexString(contentHash, true);

            var headers = new Dictionary <string, string>
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, contentHashString },
                { "content-length", payload.Length.ToString() },
                { "content-type", "text/plain" }
            };

            var uriWithoutQueryString = new Uri(uri.GetLeftPart(UriPartial.Path));
            var signer = new AWS4SignerForAuthorizationHeader
            {
                EndpointUri = uriWithoutQueryString,
                HttpMethod  = "POST",
                Service     = "iotdevicegateway",
                Region      = "us-east-1"
            };

            string AWSAccessKey = ConfigHelper.ReadSetting("accesskey");
            string AWSSecretKey = ConfigHelper.ReadSetting("secretkey");

            string queryStringWithoutLeadingQuestionMark = string.IsNullOrEmpty(uri.Query) ? string.Empty : uri.Query.Substring(1);
            var    authorization = signer.ComputeSignature(headers, queryStringWithoutLeadingQuestionMark, contentHashString, AWSAccessKey, AWSSecretKey);

            headers.Add("Authorization", authorization);

            return(headers);
        }
Beispiel #6
0
        public static async System.Threading.Tasks.Task <object> MainAsync(string uri, string AWSAccessKey, string AWSSecretKey)
        {
            var sp = uri.Split('/');

            uri = Prefix + sp.Last();

            // for a simple GET, we have no body so supply the precomputed 'empty' hash
            var headers = new Dictionary <string, string>
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 },
                { "content-type", "text/plain" },
                { "x-amz-request-payer", "requester" }
            };

            var signer = new AWS4SignerForAuthorizationHeader
            {
                EndpointUri = new Uri(uri),
                HttpMethod  = "GET",
                Service     = "s3",
                Region      = "eu-west-1"
            };

            var authorization = signer.ComputeSignature(headers,
                                                        "", // no query parameters
                                                        AWS4SignerBase.EMPTY_BODY_SHA256,
                                                        AWSAccessKey,
                                                        AWSSecretKey);

            // place the computed signature into a formatted 'Authorization' header
            // and call S3
            headers.Add("Authorization", authorization);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            foreach (var header in headers.Keys)
            {
                request.Headers[header] = headers[header];
            }

            byte[] bytes;
            using (var response = await request.GetResponseAsync())
                using (var stream = response.GetResponseStream())
                    using (var dst = new MemoryStream())
                    {
                        stream.CopyTo(dst);
                        bytes = dst.ToArray();
                    }

            var result = DataParser.ParseReplay(bytes, ParseOptions.MediumParsing);

            if (result.Item1 != DataParser.ReplayParseResult.Success || result.Item2 == null)
            {
                return($"Error parsing replay: {result.Item1}");
            }
            return(ToJson(result.Item2));
        }
Beispiel #7
0
        public static string GeneratePutRequestMethod(string entityType, string entityId, string jsonFilePath)
        {
            //Generates a JSON object from the session token JSON string
            JObject credentials = JObject.Parse(GetSessionToken().Result);

            //Get the JSON for the entity being updated and hash it for the PUT request
            var jsonObject       = File.ReadAllText(jsonFilePath);
            var encodedJsonBytes = Encoding.UTF8.GetBytes(jsonObject);
            var hashedJsonString = ComputeSHA256Hash(encodedJsonBytes);


            var endpointUri = BaseConnectionString + entityType + "/" + entityId;
            var uri         = new Uri(endpointUri);
            var headers     = new Dictionary <string, string>()
            {
                { "content-type", "application/json" },
                { "x-amz-security-token", credentials.GetValue("sessionToken").ToString() },
                { "x-api-key", ConfigSetup.ApiKey }
            };

            //Use the AWS4 signer to generate the signer and sign the request
            var signer = new AWS4SignerForAuthorizationHeader()
            {
                EndpointUri = uri,
                HttpMethod  = "PUT",
                Service     = "execute-api",
                Region      = Region
            };
            //Uses the generated accessKey and secretKey from GenerateSessionToken(), NOT FROM CONFIG
            var authorization = signer.ComputeSignature(headers, "", hashedJsonString,
                                                        credentials.GetValue("accessKey").ToString(), credentials.GetValue("secretKey").ToString());

            //Add the signed authorization to headers
            headers.Add("Authorization", authorization);
            string response = HttpHelpers.InvokeHttpRequest(uri, "PUT", headers, jsonObject);

            //Console.WriteLine(response);
            return(response);
        }
        private static void DeleteMessage(List <string> receiptHandles)
        {
            foreach (string receipt in receiptHandles)
            {
                string region = config["Region"];
                // Construct a virtual hosted style address with the bucket name part of the host address,
                // placing the region into the url if we're not using us-east-1.
                var regionUrlPart = string.Format("-{0}", region);
                //This is our QA fifo queue, replace it with your queue's url
                var endpointUri = BaseUrl + config["AccountId"] + "/" + config["QueueName"];
                //Encode the receipt handle and add it to the url
                Console.WriteLine(receipt);
                Console.WriteLine();
                var encodedReceipt    = WebUtility.UrlEncode(receipt);
                var requestParameters = "Action=DeleteMessage&ReceiptHandle=" + encodedReceipt;

                var uri     = new Uri(endpointUri + "?" + requestParameters);
                var headers = new Dictionary <string, string>()
                {
                    { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 }
                };
                //Use the AWS4 signer to generate the signer and sign the request
                var signer = new AWS4SignerForAuthorizationHeader()
                {
                    EndpointUri = uri,
                    HttpMethod  = "GET",
                    Service     = "sqs",
                    Region      = region,
                };
                var authorization = signer.ComputeSignature(headers, requestParameters, AWS4SignerBase.EMPTY_BODY_SHA256,
                                                            config["AccessKey"], config["SecretKey"]);
                headers.Add("Authorization", authorization);

                string response = HttpHelpers.InvokeHttpRequest(uri, "GET", headers, null);
                //Console.WriteLine(response);
                //Console.WriteLine("Receipt for message deleted: " + receipt);
            }
        }
Beispiel #9
0
        public ClientRequest(string objectKey, string email)
        {
            objectKey += "?email=" + email;

            var endpointUri = string.Format("http://localhost:59982/{0}", objectKey);

            var uri = new Uri(endpointUri);


            //construct the header
            var headers = new Dictionary <string, string>
            {
                { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 },
                { "content-length", email.Length.ToString() },
                { "content-type", "text/plain" }
            };

            var signer = new AWS4SignerForAuthorizationHeader
            {
                EndpointUri = uri,
                HttpMethod  = "POST",
                Service     = "",
                Region      = ""
            };

            var authorization = signer.ComputeSignature(headers,
                                                        "",   // no query parameters
                                                        AWS4SignerBase.EMPTY_BODY_SHA256,
                                                        AWSAccessKey,
                                                        AWSSecretKey);

            // place the computed signature into a formatted 'Authorization' header
            // and call S3
            headers.Add("Authorization", authorization);

            HttpHelpers.InvokeHttpRequest(uri, "POST", headers, email);
        }
Beispiel #10
0
    // Generates a HTTPS requestfor API Gateway signed with the Cognito credentials from a url using the S3 signer tool example
    // NOTE: You need to add the floders "Signers" and "Util" to the project from the S3 signer tool example: https://docs.aws.amazon.com/AmazonS3/latest/API/samples/AmazonS3SigV4_Samples_CSharp.zip
    HttpRequestMessage generateSignedRequest(string url)
    {
        var endpointUri = url;

        var uri = new Uri(endpointUri);

        var headers = new Dictionary <string, string>
        {
            { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 },
        };

        var signer = new AWS4SignerForAuthorizationHeader
        {
            EndpointUri = uri,
            HttpMethod  = "GET",
            Service     = "execute-api",
            Region      = regionString
        };

        //Extract the query parameters
        var queryParams = "";

        if (url.Split('?').Length > 1)
        {
            queryParams = url.Split('?')[1];
        }

        var authorization = signer.ComputeSignature(headers,
                                                    queryParams,
                                                    AWS4SignerBase.EMPTY_BODY_SHA256,
                                                    Client.cognitoCredentials.AccessKey,
                                                    Client.cognitoCredentials.SecretKey);

        headers.Add("Authorization", authorization);

        var request = new HttpRequestMessage
        {
            Method     = HttpMethod.Get,
            RequestUri = new Uri(url),
        };

        // Add the generated headers to the request
        foreach (var header in headers)
        {
            try
            {
                if (header.Key != null && header.Value != null)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }
            catch (Exception e)
            {
                Debug.Log("error: " + e.GetType().ToString());
            }
        }

        // Add the IAM authentication token
        request.Headers.Add("x-amz-security-token", Client.cognitoCredentials.Token);

        return(request);
    }
Beispiel #11
0
        async void Run()
        {
            var cognitoIdp     = new AmazonCognitoIdentityProviderClient();
            var region         = ConfigurationManager.AppSettings["region"];
            var userPoolId     = ConfigurationManager.AppSettings["userPoolId"];
            var clientId       = ConfigurationManager.AppSettings["clientId"];
            var identityPoolId = ConfigurationManager.AppSettings["identityPoolId"];
            var username       = ConfigurationManager.AppSettings["username"];
            var password       = ConfigurationManager.AppSettings["password"];
            var apiId          = ConfigurationManager.AppSettings["apiId"];
            var stage          = ConfigurationManager.AppSettings["stage"];
            var method         = ConfigurationManager.AppSettings["method"];
            var path           = ConfigurationManager.AppSettings["path"];
            var querystring    = ConfigurationManager.AppSettings["querystring"];

            try
            {
                var request = new AdminInitiateAuthRequest
                {
                    AuthFlow       = AuthFlowType.ADMIN_NO_SRP_AUTH,
                    ClientId       = clientId,
                    UserPoolId     = userPoolId,
                    AuthParameters = { { "USERNAME", username }, { "PASSWORD", password } }
                };

                var response = await cognitoIdp.AdminInitiateAuthAsync(request);

                var idToken = response.AuthenticationResult.IdToken;

                var credentials = new CognitoAWSCredentials(identityPoolId, RegionEndpoint.GetBySystemName(region));
                var provider    = String.Format("cognito-idp.{0}.amazonaws.com/{1}", region, userPoolId);
                credentials.AddLogin(provider, idToken);

                var immutableCredentials = await credentials.GetCredentialsAsync();

                var endpoint = String.Format("https://{0}.execute-api.{1}.amazonaws.com/{2}/{3}", apiId, region, stage, path);
                if (!String.IsNullOrWhiteSpace(querystring))
                {
                    endpoint = endpoint + "?" + querystring;
                }
                var uri = new Uri(endpoint);

                var headers = new Dictionary <string, string>
                {
                    { AWS4SignerBase.X_Amz_Content_SHA256, AWS4SignerBase.EMPTY_BODY_SHA256 },
                    { "X-Amz-Security-Token", immutableCredentials.Token },
                    { "content-type", "application/json" }
                };

                var signer = new AWS4SignerForAuthorizationHeader
                {
                    EndpointUri = uri,
                    HttpMethod  = method,
                    Service     = "execute-api",
                    Region      = region
                };

                var authorization = signer.ComputeSignature(
                    headers,
                    querystring,
                    AWS4SignerBase.EMPTY_BODY_SHA256,
                    immutableCredentials.AccessKey,
                    immutableCredentials.SecretKey);

                headers.Add("Authorization", authorization);

                HttpHelpers.InvokeHttpRequest(uri, method, headers, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred.");
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// Runs a http request to the specified endpoint
        /// </summary>
        /// <param name="endpointUri">
        /// "https://service.chime.aws.amazon.com/meetings"
        /// </param>
        /// <param name="requestType">
        /// "POST"
        /// </param>
        /// <param name="body">
        /// new { ClientRequestToken = "75341496-0878-440c-9db1-a7006c25a39f", MediaRegion = "us-east-1" }
        /// </param>
        /// <param name="service">
        /// // service = "chime"
        /// </param>
        /// <param name="region">
        /// "us-east-1"
        /// </param>
        /// <param name="queryParameters">
        /// ""
        /// </param>
        public static async Task <HttpWebResponse> Run(string endpointUri, string requestType, string service, string region, object body, string queryParameters)
        {
            var    uri            = new Uri(endpointUri);
            var    headers        = new Dictionary <string, string>();
            var    authorization  = string.Empty;
            string serializedBody = null;

            switch (requestType)
            {
            case Http.Post:
                // precompute hash of the body content
                serializedBody = JsonConvert.SerializeObject(body);
                var contentHash       = AWS4SignerBase.CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(serializedBody));
                var contentHashString = AWS4SignerBase.ToHexString(contentHash, true);

                headers.Add(AWS4SignerBase.X_Amz_Content_SHA256, contentHashString);
                headers.Add("content-length", serializedBody.Length.ToString());
                headers.Add("content-type", "text/json");

                var postSigner = new AWS4SignerForAuthorizationHeader
                {
                    EndpointUri = uri,
                    HttpMethod  = Http.Post,
                    Service     = service,
                    Region      = region
                };

                authorization = postSigner.ComputeSignature(headers, queryParameters, contentHashString, Settings.AWSAccessKey, Settings.AWSSecretKey);

                // express authorization for this as a header
                headers.Add("Authorization", authorization);

                return(await HttpHelpers.InvokeHttpRequest(uri, Http.Post, headers, serializedBody));

            case Http.Get:
                headers.Add(AWS4SignerBase.X_Amz_Content_SHA256, Settings.EMPTY_BODY_SHA256);
                headers.Add("content-type", "text/plain");

                var getSigner = new AWS4SignerForQueryParameterAuth
                {
                    EndpointUri = uri,
                    HttpMethod  = Http.Get,
                    Service     = service,
                    Region      = region
                };

                authorization = getSigner.ComputeSignature(headers, queryParameters, Settings.EMPTY_BODY_SHA256, Settings.AWSAccessKey, Settings.AWSSecretKey);

                var urlBuilder = new StringBuilder(endpointUri);
                if (!string.IsNullOrEmpty(queryParameters))
                {
                    urlBuilder.AppendFormat($"?{queryParameters}");
                    urlBuilder.AppendFormat($"&{authorization}");
                }
                else
                {
                    urlBuilder.AppendFormat($"?{authorization}");
                }

                var presignedUrl = urlBuilder.ToString();

                return(await HttpHelpers.InvokeHttpRequest(new Uri(presignedUrl), Http.Get, headers, serializedBody));

            default: throw new Exception("Unknown request type");
            }
        }