Пример #1
0
        public string ObterUrl(string remoteDirectory, string remoteFileName)
        {
            var regionUrlPart = string.Empty;

            if (this.ConfiguracoesAmazonCorretas() == false)
            {
                throw new InvalidParameterException("Não foi possivel enviar arquivo. Faltando configurações da amazon");
            }

            var region     = ContextoInfra.AmazonRegion;
            var bucketName = ContextoInfra.AmazonBucketName;

            var objectKey = Path.GetFileName(remoteFileName);

            if (string.IsNullOrEmpty(region) == false)
            {
                if (region.Equals("us-east-1", StringComparison.OrdinalIgnoreCase) == false)
                {
                    regionUrlPart = string.Format("-{0}", region);
                }
            }

            var endpointUri = string.Format("https://{0}.s3{1}.amazonaws.com/{2}/{3}",
                                            bucketName,
                                            regionUrlPart,
                                            remoteDirectory,
                                            objectKey);

            var queryParams = new StringBuilder();

            var expiresOn = DateTime.UtcNow.AddDays(1);
            var period    = Convert.ToInt64((expiresOn.ToUniversalTime() - DateTime.UtcNow).TotalSeconds);

            queryParams.AppendFormat("{0}={1}", Aws4SignerBase.XAmzExpires, AmazonStorageHelpers.UrlEncode(period.ToString()));

            var headers = new Dictionary <string, string>();

            var signer = new Aws4SignerForQueryParameterAuth
            {
                EndpointUri = new Uri(endpointUri),
                HttpMethod  = "GET",
                Service     = "s3",
                Region      = region
            };

            var authorization = signer.ComputeSignature(headers,
                                                        queryParams.ToString(),
                                                        "UNSIGNED-PAYLOAD",
                                                        ContextoInfra.AmazonAccessKey,
                                                        ContextoInfra.AmazonSecretKey);

            var urlBuilder = new StringBuilder(endpointUri.ToString());

            urlBuilder.AppendFormat("?{0}", queryParams.ToString());

            urlBuilder.AppendFormat("&{0}", authorization);

            return(urlBuilder.ToString());
        }
Пример #2
0
        public void Download(string remoteDirectory, string remoteFileName, string pathDestinoTemp)
        {
            var regionUrlPart = string.Empty;

            if (this.ConfiguracoesAmazonCorretas() == false)
            {
                throw new InvalidParameterException("Não foi possivel enviar arquivo. Faltando configurações da amazon");
            }

            var region     = ContextoInfra.AmazonRegion;
            var bucketName = ContextoInfra.AmazonBucketName;

            if (string.IsNullOrEmpty(region) == false)
            {
                if (region.Equals("us-east-1", StringComparison.OrdinalIgnoreCase) == false)
                {
                    regionUrlPart = string.Format("-{0}", region);
                }
            }

            /////https://{0}.s3{1}-accelerate.amazonaws.com/{2}/{3}
            //// https://{0}.s3{1}.amazonaws.com/{2}/{3}
            var endpointUri = string.Format("https://{0}.s3{1}-accelerate.amazonaws.com/{2}/{3}",
                                            bucketName,
                                            regionUrlPart,
                                            remoteDirectory,
                                            remoteFileName);

            var mime = MimeTypes.GetMimeType(Path.GetExtension(remoteFileName));

            var uri = new Uri(endpointUri);

            var headers = new Dictionary <string, string>
            {
                { Aws4SignerBase.XAmzContentSha256, Aws4SignerBase.EmptyBodySha256 },
                { "content-type", mime }
            };

            var signer = new Aws4SignerForAuthorizationHeader
            {
                EndpointUri = uri,
                HttpMethod  = "GET",
                Service     = "s3",
                Region      = region
            };

            var authorization = signer.ComputeSignature(
                headers,
                string.Empty,
                Aws4SignerBase.EmptyBodySha256,
                ContextoInfra.AmazonAccessKey,
                ContextoInfra.AmazonSecretKey);

            headers.Add("Authorization", authorization);

            AmazonStorageHelpers.InvokeHttpRequest(uri, "GET", headers, null, pathDestinoTemp);
        }
Пример #3
0
        /// <summary>
        /// Returns the canonicalized resource path for the service endpoint
        /// </summary>
        /// <param name="endpointUri">Endpoint to the service/resource</param>
        /// <returns>Canonicalized resource path for the endpoint</returns>
        protected string CanonicalResourcePath(Uri endpointUri)
        {
            if (string.IsNullOrEmpty(endpointUri.AbsolutePath))
            {
                return("/");
            }

            // encode the path per RFC3986
            return(AmazonStorageHelpers.UrlEncode(endpointUri.AbsolutePath, true));
        }
Пример #4
0
        /// <summary>
        /// Computes an AWS4 authorization for a request, suitable for embedding
        /// in query parameters.
        /// </summary>
        /// <param name="headers">
        /// The request headers; 'Host' and 'X-Amz-Date' will be added to this set.
        /// </param>
        /// <param name="queryParameters">
        /// Any query parameters that will be added to the endpoint. The parameters
        /// should be specified in canonical format.
        /// </param>
        /// <param name="bodyHash">
        /// Precomputed SHA256 hash of the request body content; this value should also
        /// be set as the header 'X-Amz-Content-SHA256' for non-streaming uploads.
        /// </param>
        /// <param name="awsAccessKey">
        /// The user's AWS Access Key.
        /// </param>
        /// <param name="awsSecretKey">
        /// The user's AWS Secret Key.
        /// </param>
        /// <returns>
        /// The string expressing the Signature V4 components to add to query parameters.
        /// </returns>
        public string ComputeSignature(IDictionary <string, string> headers,
                                       string queryParameters,
                                       string bodyHash,
                                       string awsAccessKey,
                                       string awsSecretKey)
        {
            var requestDateTime = DateTime.UtcNow;
            var dateTimeStamp   = requestDateTime.ToString(Iso8601BasicFormat, CultureInfo.InvariantCulture);

            if (!headers.ContainsKey("Host"))
            {
                var hostHeader = this.EndpointUri.Host;
                if (!this.EndpointUri.IsDefaultPort)
                {
                    hostHeader += ":" + this.EndpointUri.Port;
                }

                headers.Add("Host", hostHeader);
            }

            var dateStamp = requestDateTime.ToString(DateStringFormat, CultureInfo.InvariantCulture);

            var scope = string.Format("{0}/{1}/{2}/{3}",
                                      dateStamp,
                                      this.Region,
                                      this.Service,
                                      Terminator);

            var canonicalizedHeaderNames = this.CanonicalizeHeaderNames(headers);
            var canonicalizedHeaders     = this.CanonicalizeHeaders(headers);

            var paramDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrEmpty(queryParameters))
            {
                paramDictionary = queryParameters.Split('&').Select(p => p.Split('='))
                                  .ToDictionary(nameval => nameval[0],
                                                nameval => nameval.Length > 1
                                                                        ? nameval[1] : string.Empty);
            }

            paramDictionary.Add(XAmzAlgorithm, AmazonStorageHelpers.UrlEncode(string.Format("{0}-{1}", Scheme, Algorithm)));
            paramDictionary.Add(XAmzCredential, AmazonStorageHelpers.UrlEncode(string.Format("{0}/{1}", awsAccessKey, scope)));
            paramDictionary.Add(XAmzSignedHeaders, AmazonStorageHelpers.UrlEncode(canonicalizedHeaderNames));

            paramDictionary.Add(XAmzDate, AmazonStorageHelpers.UrlEncode(dateTimeStamp));

            var sb        = new StringBuilder();
            var paramKeys = new List <string>(paramDictionary.Keys);

            paramKeys.Sort(StringComparer.Ordinal);

            foreach (var p in paramKeys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }

                sb.AppendFormat("{0}={1}", p, paramDictionary[p]);
            }

            var canonicalizedQueryParameters = sb.ToString();

            var canonicalRequest = this.CanonicalizeRequest(this.EndpointUri,
                                                            this.HttpMethod,
                                                            canonicalizedQueryParameters,
                                                            canonicalizedHeaderNames,
                                                            canonicalizedHeaders,
                                                            bodyHash);

            Log.Application.InfoFormat("\nCanonicalRequest:\n{0}", canonicalRequest);

            var canonicalRequestHashBytes
                = CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest));

            var stringToSign = new StringBuilder();

            stringToSign.AppendFormat("{0}-{1}\n{2}\n{3}\n", Scheme, Algorithm, dateTimeStamp, scope);
            stringToSign.Append(ToHexString(canonicalRequestHashBytes, true));

            Log.Application.InfoFormat("\nStringToSign:\n{0}", stringToSign);

            var kha = KeyedHashAlgorithm.Create(Hmacsha256);

            kha.Key = this.DeriveSigningKey(Hmacsha256, awsSecretKey, this.Region, dateStamp, this.Service);

            var signature       = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString()));
            var signatureString = ToHexString(signature, true);

            Log.Application.InfoFormat("\nSignature:\n{0}", signatureString);

            var authString = new StringBuilder();

            var authParams = new[]
            {
                XAmzAlgorithm, XAmzCredential, XAmzDate, XAmzSignedHeaders
            };

            foreach (var p in authParams)
            {
                if (authString.Length > 0)
                {
                    authString.Append("&");
                }

                authString.AppendFormat("{0}={1}", p, paramDictionary[p]);
            }

            authString.AppendFormat("&{0}={1}", XAmzSignature, signatureString);

            var authorization = authString.ToString();

            Log.Application.InfoFormat("\nAuthorization:\n{0}", authorization);

            return(authorization);
        }
Пример #5
0
        public dynamic Postar(string pathfileName, string remoteDirectory, string remoteFileName)
        {
            var regionUrlPart = string.Empty;

            if (this.ConfiguracoesAmazonCorretas() == false)
            {
                throw new InvalidParameterException("Não foi possivel enviar arquivo. Faltando configurações da amazon");
            }

            var region     = ContextoInfra.AmazonRegion;
            var bucketName = ContextoInfra.AmazonBucketName;

            var objectKey = Path.GetFileName(remoteFileName);

            if (string.IsNullOrEmpty(region) == false)
            {
                if (region.Equals("us-east-1", StringComparison.OrdinalIgnoreCase) == false)
                {
                    regionUrlPart = string.Format("-{0}", region);
                }
            }

            var objectContent = System.IO.File.ReadAllBytes(pathfileName);

            ////"https://{0}.s3{1}.amazonaws.com/{2}/{3}" --> sem aceleracao
            ////"https://{0}.s3{1}-accelerate.amazonaws.com/{2}/{3}" --> com recurso de aceleração
            var endpointUri = string.Format(ContextoInfra.AmazonEntryPointUrl,
                                            bucketName,
                                            regionUrlPart,
                                            remoteDirectory,
                                            objectKey);

            var uri = new Uri(endpointUri);

            var contentHash = Aws4SignerBase.CanonicalRequestHashAlgorithm.ComputeHash(objectContent);

            var contentHashString = Aws4SignerBase.ToHexString(contentHash, true);

            var mime = MimeTypes.GetMimeType(Path.GetExtension(pathfileName));

            var headers = new Dictionary <string, string>
            {
                { Aws4SignerBase.XAmzContentSha256, contentHashString },
                { "content-length", objectContent.Length.ToString() },
                { "content-type", mime }
            };

            var signer = new Aws4SignerForAuthorizationHeader
            {
                EndpointUri = uri,
                HttpMethod  = "PUT",
                Service     = "s3",
                Region      = region
            };

            var authorization = signer.ComputeSignature(headers,
                                                        string.Empty,
                                                        contentHashString,
                                                        ContextoInfra.AmazonAccessKey,
                                                        ContextoInfra.AmazonSecretKey);

            headers.Add("Authorization", authorization);

            AmazonStorageHelpers.InvokeHttpRequest(uri, "PUT", headers, objectContent);
            return(null);
        }