Authenticate() public method

Implements Authenticate interface method for IAuthenticator.
public Authenticate ( IRestClient client, IRestRequest request ) : void
client IRestClient Instantiated IRestClient object
request IRestRequest Instantiated IRestRequest object
return void
Exemplo n.º 1
0
        private async Task <ResponseResult> ExecuteTaskCoreAsync(
            IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
            HttpRequestMessageBuilder requestMessageBuilder,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var startTime = DateTime.Now;

            // Logs full url when HTTPtracing is enabled.
            if (this.trace)
            {
                var fullUrl = requestMessageBuilder.RequestUri;
            }

            var v4Authenticator = new V4Authenticator(this.Secure,
                                                      this.AccessKey, this.SecretKey, this.Region,
                                                      this.SessionToken);

            requestMessageBuilder.AddOrUpdateHeaderParameter("Authorization",
                                                             v4Authenticator.Authenticate(requestMessageBuilder));

            HttpRequestMessage request = requestMessageBuilder.Request;

            ResponseResult responseResult;

            try
            {
                if (requestTimeout > 0)
                {
                    this.HttpClient.Timeout = new TimeSpan(0, 0, 0, 0, requestTimeout);
                }

                var response = await this.HttpClient.SendAsync(request,
                                                               HttpCompletionOption.ResponseHeadersRead, cancellationToken)
                               .ConfigureAwait(false);

                responseResult = new ResponseResult(request, response);
                if (requestMessageBuilder.ResponseWriter != null)
                {
                    requestMessageBuilder.ResponseWriter(responseResult.ContentStream);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                responseResult = new ResponseResult(request, e);
            }

            this.HandleIfErrorResponse(responseResult, errorHandlers, startTime);
            return(responseResult);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Constructs a RestRequest. For AWS, this function has the side-effect of overriding the baseUrl
        /// in the RestClient with region specific host path or virtual style path.
        /// </summary>
        /// <param name="method">HTTP method</param>
        /// <param name="bucketName">Bucket Name</param>
        /// <param name="objectName">Object Name</param>
        /// <param name="headerMap">headerMap</param>
        /// <param name="contentType">Content Type</param>
        /// <param name="body">request body</param>
        /// <param name="resourcePath">query string</param>
        /// <returns>A RestRequest</returns>
        /// <exception cref="BucketNotFoundException">When bucketName is invalid</exception>
        internal async Task <RestRequest> CreateRequest(Method method, string bucketName      = null, string objectName = null,
                                                        Dictionary <string, string> headerMap = null,
                                                        string contentType = "application/octet-stream",
                                                        object body        = null, string resourcePath = null)
        {
            string region = string.Empty;

            if (bucketName != null)
            {
                utils.ValidateBucketName(bucketName);
                region = await GetRegion(bucketName).ConfigureAwait(false);
            }

            if (objectName != null)
            {
                utils.ValidateObjectName(objectName);
            }

            // Start with user specified endpoint
            string host = this.BaseUrl;

            this.restClient.Authenticator = new V4Authenticator(this.Secure, this.AccessKey, this.SecretKey, region: string.IsNullOrEmpty(this.Region)?region:this.Region, sessionToken: this.SessionToken);

            // This section reconstructs the url with scheme followed by location specific endpoint (s3.region.amazonaws.com)
            // or Virtual Host styled endpoint (bucketname.s3.region.amazonaws.com) for Amazon requests.
            string resource     = string.Empty;
            bool   usePathStyle = false;

            if (bucketName != null)
            {
                if (s3utils.IsAmazonEndPoint(this.BaseUrl))
                {
                    usePathStyle = false;

                    if (method == Method.PUT && objectName == null && resourcePath == null)
                    {
                        // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com
                        usePathStyle = true;
                    }
                    else if (resourcePath != null && resourcePath.Contains("location"))
                    {
                        // use path style for location query
                        usePathStyle = true;
                    }
                    else if (bucketName != null && bucketName.Contains(".") && this.Secure)
                    {
                        // use path style where '.' in bucketName causes SSL certificate validation error
                        usePathStyle = true;
                    }

                    if (usePathStyle)
                    {
                        resource += utils.UrlEncode(bucketName) + "/";
                    }
                }
                else
                {
                    resource += utils.UrlEncode(bucketName) + "/";
                }
            }

            // Set Target URL
            Uri requestUrl = RequestUtil.MakeTargetURL(this.BaseUrl, this.Secure, bucketName, region, usePathStyle);

            SetTargetURL(requestUrl);

            if (objectName != null)
            {
                resource += utils.EncodePath(objectName);
            }

            // Append query string passed in
            if (resourcePath != null)
            {
                resource += resourcePath;
            }

            RestRequest request = new RestRequest(resource, method);

            if (body != null)
            {
                request.AddParameter(contentType, body, RestSharp.ParameterType.RequestBody);
            }

            if (headerMap != null)
            {
                foreach (var entry in headerMap)
                {
                    request.AddHeader(entry.Key, entry.Value);
                }
            }

            if (this.Provider != null)
            {
                AccessCredentials creds = await this.Provider.GetCredentialsAsync();

                bool isAWSProvider = (this.Provider is AWSEnvironmentProvider) ||
                                     (this.Provider is ChainedProvider chained && chained.CurrentProvider is AWSEnvironmentProvider);
                bool isAWSSessionTokenAvailable = isAWSProvider && (!string.IsNullOrEmpty(creds.SessionToken) && !string.IsNullOrWhiteSpace(creds.SessionToken));
                if (isAWSSessionTokenAvailable)
                {
                    request.AddHeader("X-Amz-Security-Token", creds.SessionToken);
                }
                authenticator.Authenticate(restClient, request);
            }

            return(request);
        }