/// <summary>
 /// Does the authentication module supports pre-authentication?
 /// </summary>
 /// <param name="client">Client executing this request</param>
 /// <param name="request">Request to authenticate</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <returns>true when the authentication module supports pre-authentication</returns>
 public bool CanPreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
 {
     var cred = credentials?.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
     if (cred == null)
         return false;
     return true;
 }
예제 #2
0
        internal ApiOptionalResponse <R> Get <R>(string path, ISearchFilter filter = null)
            where R : ApiObject
        {
            var request = CreateRequest(path, Method.GET, filter);

            SetTokenAndUri();
#if DEBUG
            var uri = Client.BuildUri(request);
            Api.DebugList.Add(uri.ToString());
#endif
            var response = Client.Execute(request);
            if (!response.IsSuccessful)
            {
                throw new ApiErrorException(response.StatusCode, response.Content);
            }
#if DEBUG
            Api.DebugResponseList.Add(response);
#endif
            var asRequestResponse = serializerDeserializer.Deserialize <RequestResponse <R> >(response);

            if ("error" == asRequestResponse.Status)
            {
                return(new ApiOptionalResponse <R>
                {
                    Exception = asRequestResponse.Messages.ContainsKey("general")
                        ? new ApiErrorException(asRequestResponse.Messages["general"])
                        : new ApiErrorException(asRequestResponse.Messages)
                });
            }

            return(new ApiOptionalResponse <R> {
                Value = serializerDeserializer.Deserialize <R>(response)
            });
        }
예제 #3
0
        /// <inheritdoc cref="IApiClient.MakeApiRequest" />
        public async Task <ApiResponse> MakeApiRequest(ApiRequest request, CancellationToken cancellationToken = default)
        {
            // Prepare the request
            var restRequest = PrepareRequest(request);

            // Send the request
            var restResponse = await _restClient.ExecuteTaskAsync(restRequest, cancellationToken);

            // If the response is unsuccessful with an Unauthorized response, and we are expected to be using a Machine Token, refresh the token and try again
            if (!restResponse.IsSuccessful && request.Authorization == null && request.UseMachineToken && restResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                _machineToken = null;
                restRequest.AddOrUpdateParameter(HeaderNames.Authorization, $"Bearer {MachineToken.AccessToken}", ParameterType.HttpHeader);
                restResponse = await _restClient.ExecuteTaskAsync(restRequest, cancellationToken);
            }

            // Deal with the response, either by failing, or returning a success object
            if (restResponse.IsSuccessful)
            {
                return(ApiResponse.FromRestResponse(restResponse));
            }

            switch (restResponse.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                throw new UnauthorizedException();

            default:
                throw new RestException(_restClient.BuildUri(restRequest).ToString(), restResponse.StatusCode, restResponse.Content, request.Body);
            }
        }
        public T DoAuthenticatedRequest <T>(IRestRequest request)
            where T : new()
        {
            IRestClient client = restClientFactory.Create();

            _logger.Log(string.Format("Request: {0}", client.BuildUri(request)));
            IRestResponse <T> response = client.Execute <T>(request);

            _logger.Log(string.Format("Response: {0} - {1}", response.StatusCode, StringHelpers.Truncate(response.Content, 100)));

            // If login session has expired, try to login, and then re-execute the original request
            if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadRequest)
            {
                _logger.Log("Try to re-authenticate");
                if (!ReAuthenticate())
                {
                    throw new RequestDeniedException();
                }

                _logger.Log(string.Format("Authenticated. Resend request: {0}", client.BuildUri(request)));
                response = client.Execute <T>(request);
                _logger.Log(string.Format("Response: {0} - {1}", response.StatusCode, StringHelpers.Truncate(response.Content, 100)));
            }

            if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
            {
                ErrorMessage = response.ErrorMessage;
                throw new RequestDeniedException();
            }

            ErrorMessage = "";
            return(response.Data);
        }
예제 #5
0
        /// <summary>
        /// Get the REST requests relative address (for HTTP request message)
        /// </summary>
        /// <param name="client">REST client</param>
        /// <param name="request">REST request</param>
        /// <returns>The relative request message URL</returns>
        protected virtual Uri GetMessageAddress(IRestClient client, IRestRequest request)
        {
            var fullUrl = client.BuildUri(request);
            var url     = client.BuildUri(null, false).MakeRelativeUri(fullUrl);

            return(url);
        }
예제 #6
0
        public async Task <bool> PostFileAsync(RequestInfoEventArgs requestInfo, Stream stream)
        {
            IRestClient client = CreateRestClient();

            client.CookieContainer = new CookieContainer();

            var heartBeat    = new RestRequest(_config.PingResource, Method.GET);
            var heartBeatUrl = client.BuildUri(heartBeat); // For debugging purposes.

            _logger.LogDebug($"Will perform a GET to Heartbeat-endpoint using {heartBeatUrl}.");
            var heartBeatResponse = await client.ExecuteGetAsync(heartBeat);

            if (!heartBeatResponse.IsSuccessful)
            {
                // Possible error handling here.
                // If you are unable to ping the heartbeat endpoint there's probably
                // something wrong with the certificate.
                _logger.LogWarning("Get to Heartbeat-endpoint was not successful. Will abort.");
                return(false);
            }

            _logger.LogDebug("Get to Heartbeat-endpoint was successful.");

            var cookies = client.CookieContainer.GetCookies(new Uri(_config.BaseUrl));

            IRestRequest request = CreateFileUploadRequest(requestInfo, stream);

            foreach (Cookie restResponseCookie in cookies)
            {
                request.AddCookie(restResponseCookie.Name, restResponseCookie.Value);
            }

            var url = client.BuildUri(request);

            _logger.LogInformation($"Posting file to: {url}");
            var response = await client.ExecutePostAsync <FileUploadResponse>(request);

            if (response.StatusCode == HttpStatusCode.OK && response.Data != null)
            {
                _logger.LogInformation($"File successfully posted. Thank you. The id for your deliveryId is: {response.Data.DeliveryId}.");

                // You might want to return the deliveryId for further processing.
                // For the moment we simply return true to indicate success.
                return(true);
            }

            _logger.LogInformation($"Post failed. Response: {response.ErrorMessage}");
            return(false);
        }
        public void LogRequest(IRestClient restClient, IRestRequest request, IRestResponse response)
        {
            var requestToLog = new
            {
                resource   = request.Resource,
                parameters = request.Parameters.Select(parameter => new
                {
                    name  = parameter.Name,
                    value = parameter.Value,
                    type  = parameter.Type.ToString()
                }),
                body   = request.Body,
                method = request.Method.ToString(),
                uri    = restClient.BuildUri(request)
            };

            var responseToLog = new
            {
                statusCode   = response.StatusCode,
                content      = response.Content,
                headers      = response.Headers,
                responseUri  = response.ResponseUri,
                errorMessage = response.ErrorMessage
            };

            string messageToLog = string.Format("Request completed,\nRequest:\n{0},\nResponse:\n{1}",
                                                JsonConvert.SerializeObject(requestToLog),
                                                JsonConvert.SerializeObject(responseToLog));

            TestContext.Out.WriteLine(messageToLog);
        }
예제 #8
0
        /// <summary>
        /// Wrapper for calling a request and parsing the response if there is an error.
        /// </summary>
        /// <param name="client">The client to use for making the call.</param>
        /// <param name="retryPolicy">The retry policy to use for this request.</param>
        /// <param name="request">The details of the request to make.</param>
        /// <param name="nullOn404">Set if we should return NULL on a 404, false will cause an exception to get thrown.</param>
        /// <returns>The IRestResponse or NULL if the entity was not found.</returns>
        public static IRestResponse ExecuteRequestFor(
            this IRestClient client,
            IRetryPolicy retryPolicy,
            IRestRequest request,
            bool nullOn404)
        {
            var resource = client.BuildUri(request);

            IRestResponse response =
                retryPolicy.Execute(
                    attempt =>
            {
                s_log.Trace(m => m("REQUESTING {0}: {1}  (ATTEMPT: {2})", request.Method, resource, attempt));

                var res = client.Execute(request);

                s_log.Debug(m => m("{0} {1} - {2}", request.Method, res.StatusCode, resource));

                if (!res.StatusCode.IsSuccessCode())
                {
                    return(HandleErrorResponse(request, res, resource, nullOn404));
                }

                return(res);
            });

            return(response);
        }
예제 #9
0
        /// <summary>
        /// Logs the request sent to server and corresponding response
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="durationMs"></param>
        private void LogRequest(IRestRequest request, IRestResponse response, double durationMs)
        {
            var requestToLog = new RequestToLog
            {
                resource = request.Resource,
                // Parameters are custom anonymous objects in order to have the parameter type as a nice string
                // otherwise it will just show the enum value
                parameters = request.Parameters.Select(parameter => new RequestParameter
                {
                    name  = parameter.Name,
                    value = parameter.Value,
                    type  = parameter.Type.ToString()
                }),
                // ToString() here to have the method as a nice string otherwise it will just show the enum value
                method = request.Method.ToString(),
                // This will generate the actual Uri used in the request
                uri = restClient.BuildUri(request)
            };

            var responseToLog = new ResponseToLog
            {
                statusCode = response.StatusCode,
                content    = response.Content,
                headers    = response.Headers,
                // The Uri that actually responded (could be different from the requestUri if a redirection occurred)
                responseUri  = response.ResponseUri,
                errorMessage = response.ErrorMessage,
                durationMs   = durationMs
            };

            this.logger.LogRequest(requestToLog, responseToLog, durationMs);
        }
 private void LogRequest(IRestRequest request, IRestResponse response, long durationMs)
 {
     _logger.Trace(() =>
     {
         var requestToLog = new
         {
             resource = request.Resource,
             // Parameters are custom anonymous objects in order to have the parameter type as a nice string
             // otherwise it will just show the enum value
             parameters = request.Parameters.Select(parameter => new
             {
                 name  = parameter.Name,
                 value = parameter.Value,
                 type  = parameter.Type.ToString()
             }),
             // ToString() here to have the method as a nice string otherwise it will just show the enum value
             method = request.Method.ToString(),
             // This will generate the actual Uri used in the request
             uri = _restClient.BuildUri(request),
         };
         var responseToLog = new
         {
             statusCode = response.StatusCode,
             content    = response.Content,
             headers    = response.Headers,
             // The Uri that actually responded (could be different from the requestUri if a redirection occurred)
             responseUri  = response.ResponseUri,
             errorMessage = response.ErrorMessage,
         };
         return(string.Format("Request completed in {0} ms, Request: {1}, Response: {2}",
                              durationMs, JsonConvert.SerializeObject(requestToLog),
                              JsonConvert.SerializeObject(responseToLog)));
     });
 }
예제 #11
0
        public async Task Authenticate(IRestClient client, IRestRequest request)
        {
            var uri  = client.BuildUri(request);
            var path = uri.AbsolutePath;

            if (path.EndsWith("/time") && path.Length <= 8)
            {
                request.AddHeader("CB-VERSION", Constants.ApiVersionDate);
                return;
            }
            string timestamp;

            if (_useTimeApi)
            {
                var timeReq = new RestRequest("/time", Method.GET)
                {
                    Serializer = new JsonNetSerializer(_jsonSettings)
                };

                var timeResp = await client.Execute <CoinbaseResponse <Time> >(timeReq);

                timestamp = timeResp.Data.Data.Epoch.ToString();
            }
            else
            {
                timestamp = EpochConverter.GetCurrentUnixTimestampSeconds().ToString(CultureInfo.InvariantCulture);
            }

            var method = request.Method.ToString().ToUpper();

            var body = string.Empty;

            if (request.Method != Method.GET)
            {
                var param = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
                if (param != null && param.Value?.ToString() != "null" &&
                    !string.IsNullOrWhiteSpace(param?.Value?.ToString()))
                {
                    body = Encoding.UTF8.GetString((byte[])param.Value);
                }
            }
            else
            {
                path = uri.PathAndQuery;
            }


            var hmacSig = GenerateSignature(timestamp, method, path, body, _apiSecret);

            // For GDAX api only
            if (!string.IsNullOrEmpty(_passphrase))
            {
                request.AddHeader("CB-ACCESS-PASSPHRASE", _passphrase);
            }

            request.AddHeader("CB-ACCESS-KEY", _apiKey)
            .AddHeader("CB-ACCESS-SIGN", hmacSig)
            .AddHeader("CB-ACCESS-TIMESTAMP", timestamp)
            .AddHeader("CB-VERSION", Constants.ApiVersionDate);
        }
예제 #12
0
        private DelugeResponse <TResult> ProcessRequest <TResult>(IRestClient client, string action, object[] arguments)
        {
            var request = new RestRequest(Method.POST);

            request.Resource      = "json";
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Accept-Encoding", "gzip,deflate");

            var data = new Dictionary <string, object>();

            data.Add("id", GetCallId());
            data.Add("method", action);

            if (arguments != null)
            {
                data.Add("params", arguments);
            }

            request.AddBody(data);

            _logger.Debug("Url: {0} Action: {1}", client.BuildUri(request), action);
            var response = client.ExecuteAndValidate <DelugeResponse <TResult> >(request);

            return(response);
        }
        /// <summary>
        /// Modifies the request to ensure that the authentication requirements are met.
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials used for the authentication</param>
        /// <returns>The task the authentication is performed on</returns>
        public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
        {
            if (credentials == null)
            {
                throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
            }

            var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);

            if (cred == null)
            {
                throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
            }

            request.Parameters.AddOrUpdate(new Parameter {
                Type = _parameterType, Name = _usernameKey, Value = cred.UserName, ValidateOnAdd = false
            });
            request.Parameters.AddOrUpdate(new Parameter {
                Type = _parameterType, Name = _passwordKey, Value = cred.Password, ValidateOnAdd = false
            });

#if USE_TASKEX
            return(TaskEx.FromResult(0));
#else
            return(Task.FromResult(0));
#endif
        }
예제 #14
0
        /// <summary>
        /// Method implementing point of entry for RestSharp authentication.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="request"></param>
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            DateTime requestDT  = DateTime.Now.ToUniversalTime();
            string   authHeader = null;

            request.AddOrUpdateParameter("Date", requestDT.ToString("R"), ParameterType.HttpHeader);
            Uri finalUri = client.BuildUri(request);

            if (request.Method == Method.POST)
            {
                MD5    md5        = MD5.Create();
                string postData   = request.Parameters.Single(p => p.Name == "application/json").Value.ToString();
                string contentMD5 = postData == null ? "" : GetMd5(md5, postData);
                if (contentMD5 != "")
                {
                    request.AddOrUpdateParameter("Content-MD5", contentMD5, ParameterType.HttpHeader);
                }

                authHeader = GetAuthHeader("application/json", contentMD5, finalUri.PathAndQuery, requestDT);
            }
            else
            {
                authHeader = GetAuthHeader("", "", finalUri.PathAndQuery, requestDT);
            }
            //HMAC Header
            request.AddOrUpdateParameter("Authorization", string.Format("APIAuth {0}", authHeader), ParameterType.HttpHeader);
        }
예제 #15
0
        private string GetAuthToken(IRestClient client)
        {
            var request = new RestRequest();

            request.RequestFormat = DataFormat.Json;
            request.Resource      = "/gui/token.html";

            _logger.Debug("Url: {0}", client.BuildUri(request));
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new DownloadClientAuthenticationException("Failed to authenticate");
            }

            response.ValidateResponse(client);

            var xmlDoc = new System.Xml.XmlDocument();

            xmlDoc.LoadXml(response.Content);

            var authToken = xmlDoc.FirstChild.FirstChild.InnerText;

            _logger.Debug("uTorrent AuthToken={0}", authToken);

            return(authToken);
        }
예제 #16
0
        public void Intercept(IInvocation invocation)
        {
            // Build Request
            var methodInfo = new RestMethodInfo(invocation.Method);
            var request    = new RequestBuilder(methodInfo, invocation.Arguments).Build();
            var test       = _restClient.BuildUri(request);

            // Execute request
            var genericTypeArguments = invocation.Method.ReturnType.GetGenericArguments();

            if (genericTypeArguments.Length > 0)
            {
                // We have to find the method manually due to limitations of GetMethod()
                var method = _restClient.GetType().GetMethods()
                             .Where(m => m.Name == "Execute").First(m => m.IsGenericMethod);
                var genericTypeArgument = genericTypeArguments.Length > 0 ? genericTypeArguments[0] : null;
                var generic             = method.MakeGenericMethod(genericTypeArgument);
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                invocation.ReturnValue = generic.Invoke(_restClient, new object[] { request });
            }
            else
            {
                var method = _restClient.GetType().GetMethods()
                             .Where(m => m.Name == "Execute").First(m => !m.IsGenericMethod);
                invocation.ReturnValue = method.Invoke(_restClient, new object[] { request });
            }
        }
예제 #17
0
        /// <summary>
        /// Makes a request to the Heartbeat-endpoint
        /// </summary>
        public async Task PerformHeartBeatAsync()
        {
            try
            {
                IRestClient client  = CreateRestClient();
                var         request = new RestRequest
                {
                    Method   = Method.GET,
                    Resource = _config.PingResource
                };

                var url = client.BuildUri(request);
                _logger.LogInformation($"Making request to url: {url}");

                IRestResponse result = await client.ExecuteGetAsync(request);

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    _logger.LogInformation("Successful heartbeat from server.");
                }
                else
                {
                    _logger.LogWarning($"Failed to get a heartbeat from the server. StatusCode: {result.StatusCode}. Message: {result.ErrorMessage}");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error when checking heartbeat.");
            }
        }
예제 #18
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var uri  = client.BuildUri(request);
            var path = uri.AbsolutePath;

            if (path.EndsWith("/time") && path.Length <= 8)
            {
                request.AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
                return;
            }
            string timestamp = null;

            if (useTimeApi)
            {
                var timeReq = new RestRequest("/time", Method.GET)
                {
                    JsonSerializer = new JsonNetSerializer(jsonSettings)
                };

                var timeResp = client.Execute <CoinbaseResponse <Time> >(timeReq);
                timestamp = timeResp.Data.Data.Epoch.ToString();
            }
            else
            {
                timestamp = GetCurrentUnixTimestampSeconds().ToString(CultureInfo.InvariantCulture);
            }

            var method = request.Method.ToString().ToUpper(CultureInfo.InvariantCulture);

            var body = string.Empty;

            if (request.Method != Method.GET)
            {
                var param = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
                //if( param != null && param?.Value?.ToString() != "null" && !string.IsNullOrWhiteSpace(param?.Value?.ToString()) )
                if (param != null)
                {
                    if (param.Value != null && param.Value.ToString() != "null")
                    {
                        if (param.Value.ToString() != "")
                        {
                            body = param.Value.ToString();
                        }
                    }
                }
            }
            else
            {
                path = uri.PathAndQuery;
            }


            var hmacSig = GenerateSignature(timestamp, method, path, body, this.apiSecret);

            request.AddHeader("CB-ACCESS-KEY", this.apiKey)
            .AddHeader("CB-ACCESS-SIGN", hmacSig)
            .AddHeader("CB-ACCESS-TIMESTAMP", timestamp)
            .AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
        }
예제 #19
0
        /// <summary>
        /// Presigns any input client object with a requested expiry.
        /// </summary>
        /// <param name="client">Instantiated client</param>
        /// <param name="request">Instantiated request</param>
        /// <param name="expires">Expiration in seconds</param>
        /// <param name="region">Region of storage</param>
        /// <param name="sessionToken">Value for session token</param>
        /// <param name="reqDate"> Optional request date and time in UTC</param>
        /// <returns>Presigned url</returns>
        internal string PresignURL(IRestClient client, IRestRequest request, int expires, string region = "", string sessionToken = "", DateTime?reqDate = null)
        {
            var signingDate = reqDate ?? DateTime.UtcNow;

            if (string.IsNullOrWhiteSpace(region))
            {
                region = this.GetRegion(client.BaseUrl.Host);
            }

            Uri    requestUri   = client.BuildUri(request);
            string requestQuery = requestUri.Query;

            SortedDictionary <string, string> headersToSign = this.GetHeadersToSign(request);

            if (!string.IsNullOrEmpty(sessionToken))
            {
                headersToSign["X-Amz-Security-Token"] = sessionToken;
            }

            if (requestQuery.Length > 0)
            {
                requestQuery += "&";
            }
            requestQuery += "X-Amz-Algorithm=AWS4-HMAC-SHA256&";
            requestQuery += "X-Amz-Credential="
                            + Uri.EscapeDataString(this.accessKey + "/" + this.GetScope(region, signingDate))
                            + "&";
            requestQuery += "X-Amz-Date="
                            + signingDate.ToString("yyyyMMddTHHmmssZ")
                            + "&";
            requestQuery += "X-Amz-Expires="
                            + expires
                            + "&";
            requestQuery += "X-Amz-SignedHeaders=host";

            var presignUri = new UriBuilder(requestUri)
            {
                Query = requestQuery
            }.Uri;
            string canonicalRequest = this.GetPresignCanonicalRequest(request.Method, presignUri, headersToSign);
            string headers          = string.Concat(headersToSign.Select(p => $"&{p.Key}={utils.UrlEncode(p.Value)}"));

            byte[] canonicalRequestBytes = System.Text.Encoding.UTF8.GetBytes(canonicalRequest);
            string canonicalRequestHash  = this.BytesToHex(ComputeSha256(canonicalRequestBytes));
            string stringToSign          = this.GetStringToSign(region, signingDate, canonicalRequestHash);

            byte[] signingKey        = this.GenerateSigningKey(region, signingDate);
            byte[] stringToSignBytes = System.Text.Encoding.UTF8.GetBytes(stringToSign);
            byte[] signatureBytes    = this.SignHmac(signingKey, stringToSignBytes);
            string signature         = this.BytesToHex(signatureBytes);

            // Return presigned url.
            var signedUri = new UriBuilder(presignUri)
            {
                Query = $"{requestQuery}{headers}&X-Amz-Signature={signature}"
            };

            return(signedUri.ToString());
        }
예제 #20
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="client">RestSharp client.</param>
 /// <param name="request">Request object.</param>
 public RequestData(IRestRequest request, IRestClient client)
 {
     Method     = request.Method.ToString();
     Uri        = client.BuildUri(request);
     Resource   = request.Resource;
     Parameters = ParameterData.GetParameterDataList(request.Parameters);
     Body       = request.Body;
 }
예제 #21
0
        public async Task <IRestResponse> ExecuteAsync(IRestRequest request)
        {
            if (!string.IsNullOrEmpty(_subKey))
            {
                request.AddQueryParameter("subscription-key", _subKey);
            }

            _logger.Info(string.Format("Request to: {0} performed", _restClient.BuildUri(request)));

            var           startTime = DateTimeOffset.UtcNow;
            var           sw        = Stopwatch.StartNew();
            IRestResponse response  = await _restClient.ExecuteAsync(request, request.Method, CancellationToken.None);

            sw.Stop();

            // Retry once in case of unsuccessful calls
            if (ShouldBeRetried(response))
            {
                TrackExceptionToAppInsights(request, response, sw.Elapsed, true);
                await Task.Delay(RetryDelayMs);

                startTime = DateTimeOffset.UtcNow;
                sw.Restart();
                response = await _restClient.ExecuteAsync(request, request.Method, CancellationToken.None);

                sw.Stop();
            }

            if (response == null)
            {
                response = new RestResponse
                {
                    StatusCode   = HttpStatusCode.BadRequest,
                    ErrorMessage = "API response was null"
                };
            }

            if (!response.IsSuccessful)
            {
                TrackExceptionToAppInsights(request, response, sw.Elapsed);
                _logger.Error(string.Format("Request to: {0} returned with Error Code: {1} and response: {2}", _restClient.BuildUri(request), response.StatusCode, response.ErrorMessage));
            }

            return(response);
        }
예제 #22
0
        public IObservable <BitmapImage> FetchImageForAlbum(Song song)
        {
            var rq = new RestRequest(String.Format("images/art/{0}.png", song.id));

            var fullUrl = client.BuildUri(rq).ToString();

            this.Log().Info("Fetching URL for image: {0}", fullUrl);
            return(cache.LoadImageFromUrl(fullUrl));
        }
예제 #23
0
        /// <summary>
        /// Executes the specified request against the alpha stream rest server
        /// </summary>
        /// <typeparam name="T">The response type</typeparam>
        /// <param name="request">The request object that will be transformed into a rest request</param>
        /// <returns>The response</returns>
        public async Task <T> Execute <T>(IRequest <T> request)
        {
            var restRequest = request.ToRestRequest();

            if (RequestTracingEnabled)
            {
                var pathAndQuery = client.BuildUri(restRequest).ToString().Replace(DefaultBaseUrl, string.Empty);
                Trace.TraceInformation($"{restRequest.Method} {pathAndQuery}");

                var body = restRequest.GetBody();
                if (body != null)
                {
                    Trace.TraceInformation($"Request Body: {Environment.NewLine}{body.FormatAsJsonIfPossible()}");
                }
            }

            // add required authorization headers
            var stamp = GetUnixTimeStamp();

            restRequest.AddHeader("Timestamp", stamp.ToString());
            client.Authenticator = new HttpBasicAuthenticator(
                credentials.ClientId,
                credentials.CreateSecureHash(stamp)
                );

            var taskCompletionSource = new TaskCompletionSource <JToken>();

            client.ExecuteAsync(restRequest, response =>
            {
                if (ResponseTracingEnabled)
                {
                    Trace.TraceInformation("Response Body: " + Environment.NewLine + response.Content.FormatAsJsonIfPossible());
                    LastRestResponse = response.Content;
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        taskCompletionSource.SetResult(JToken.Parse(response.Content));
                        return;
                    }
                    catch (Exception exception)
                    {
                        Trace.TraceError("Error Deserializing Response: " + Environment.NewLine + exception.ToString());
                    }
                }

                // either received a non 200 status code or failed to parse as the requested type
                taskCompletionSource.SetException(AlphaServiceException.ForResponse(response));
            });

            var jtokenResponse = await taskCompletionSource.Task.ConfigureAwait(false);

            return(jtokenResponse.ToObject <T>());
        }
예제 #24
0
        private static void HandleResponse(IRestClient client, IRestRequest request, IRestResponse response)
        {
            if (!EnsureSuccessStatusCode(response))
            {
                var path = client.BuildUri(request).AbsoluteUri;

                //ILog log = LogManager.GetLogger(typeof(RestSharpExtensions));
                //log.ErrorFormat("BadStatus: {0} {1}", path, (int)response.StatusCode);
            }
        }
예제 #25
0
        /// <summary>
        /// Does the authentication module supports pre-authentication?
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <returns>true when the authentication module supports pre-authentication</returns>
        public bool CanPreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
        {
            var cred = credentials?.GetCredential(client.BuildUri(request, false), AuthenticationMethod);

            if (cred == null)
            {
                return(false);
            }
            return(true);
        }
예제 #26
0
        public string GetAuthenticationUrl()
        {
            var request = new RestRequest(spotifyConfiguration.AuthorizeUrl, Method.GET);

            request.AddParameter("client_id", spotifyConfiguration.ClientId);
            request.AddParameter("response_type", "code");
            request.AddParameter("redirect_uri", spotifyConfiguration.RedirectUri);

            return(restClient.BuildUri(request).AbsoluteUri);
        }
예제 #27
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var body = GetBody(request);

            var httpRequestData = new RestAuthorizeRequestData(body, client.BuildUri(request), request.Method);

            var authorizationHeaderValue = AuthorizationHeaderFactory.Get(httpRequestData);

            request.AddParameter("Authorization", authorizationHeaderValue, ParameterType.HttpHeader);
        }
예제 #28
0
        /// <summary>
        /// Authenticates the specified client and request using Hawk authentication.
        /// </summary>
        /// <param name="client">The RestSharp client instance use to submit the request.</param>
        /// <param name="request">The RestSharp request to execute.</param>
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var uri = client.BuildUri(request);
            var portSuffix = uri.Port != 80 ? ":" + uri.Port : "";
            var host = uri.Host + portSuffix;
            var method = request.Method.ToString();

            var header = Hawk.GetAuthorizationHeader(host, method, uri, _credential);

            request.AddHeader("Authorization", "Hawk " + header);
        }
예제 #29
0
        public static void EnsureResponseWasSuccessful(this IRestClient client, IRestRequest request, IRestResponse response)
        {
            if (response.IsSuccessful())
            {
                return;
            }

            var requestUri = client.BuildUri(request);

            throw RestException.CreateException(requestUri, response);
        }
예제 #30
0
        /// <summary>
        /// Authenticates the specified client and request using Hawk authentication.
        /// </summary>
        /// <param name="client">The RestSharp client instance use to submit the request.</param>
        /// <param name="request">The RestSharp request to execute.</param>
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var uri        = client.BuildUri(request);
            var portSuffix = uri.Port != 80 ? ":" + uri.Port : "";
            var host       = uri.Host + portSuffix;
            var method     = request.Method.ToString();

            var header = Hawk.GetAuthorizationHeader(host, method, uri, _credential);

            request.AddHeader("Authorization", "Hawk " + header);
        }
예제 #31
0
        protected T Execute <T>(IRestClient client) where T : new()
        {
            var response = client.Execute <T>(this);
            var fullUrl  = client.BuildUri(this);

            if (response.ErrorException != null)
            {
                throw Reggora.RaiseRequestErrorToException(response.StatusCode, response.ErrorException);
            }

            return(response.Data);
        }
예제 #32
0
        /// <summary>
        /// Build an OAuth authorization URL with the given OAuth token and callback URL.
        /// </summary>
        /// <param name="oauthToken">The OAuth request token to authorize.</param>
        /// <param name="callbackUrl">The URL Goodreads will redirect back to.</param>
        /// <returns>A URL to authorize an OAuth request token.</returns>
        public string BuildAuthorizeUrl(string oauthToken, string callbackUrl)
        {
            var request = new RestRequest("oauth/authorize");

            request.AddParameter("oauth_token", oauthToken);

            if (!string.IsNullOrEmpty(callbackUrl))
            {
                request.AddParameter("oauth_callback", callbackUrl);
            }

            return(Client.BuildUri(request).ToString());
        }
 /// <summary>
 /// Modifies the request to ensure that the authentication requirements are met.
 /// </summary>
 /// <param name="client">Client executing this request</param>
 /// <param name="request">Request to authenticate</param>
 /// <param name="credentials">The credentials used for the authentication</param>
 /// <returns>The task the authentication is performed on</returns>
 public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
 {
     return Task.Factory.StartNew(() =>
     {
         if (credentials == null)
             throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
         var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
         if (cred == null)
             throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
         request.AddParameter(_usernameKey, cred.UserName, _parameterType);
         request.AddParameter(_passwordKey, cred.Password, _parameterType);
     });
 }
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var nonce = GetNonce();

            var url = client.BuildUri(request);

            request.AddParameter("nonce", nonce, ParameterType.GetOrPost);
            var @params = request.Parameters.Where(p => p.Type == ParameterType.GetOrPost)
                .Select(p => p.Name.UrlEncode() + "=" + p.Value.ToString().UrlEncode());

            var hmacSig = GenerateSignature(string.Join("&", @params.ToArray()), this.apiSecret);

            request.AddHeader("x-api-key", this.apiKey)
                   .AddHeader("x-api-sign", hmacSig);
        }
        private string GenerateSignature(IRestClient client, IRestRequest request)
        {
            var uri = client.BuildUri(request);
            var query = uri.Query;

            if (!string.IsNullOrEmpty(query))
                query = query.Substring(1);

            var encoding = new System.Text.ASCIIEncoding();
            var key = encoding.GetBytes(_apiKey);
            var myhmacsha256 = new HMACSHA256(key);
            var hashValue = myhmacsha256.ComputeHash(encoding.GetBytes(query));
            var hmac64 = Convert.ToBase64String(hashValue);
            return hmac64;
        }
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            request.Credentials = new NetworkCredential(_user, _pass);

            // TODO: Figure out how to remove the if.. currently PUT does not work if the DigestAuthFixer is in place
            if (request.Method == Method.GET)
            {
                var url = client.BuildUri(request).ToString();
                var uri = new Uri(url);

                var digestAuthFixer = new DigestAuthFixer(client.BaseUrl, _user, _pass);
                digestAuthFixer.GrabResponse(uri.PathAndQuery);
                var digestHeader = digestAuthFixer.GetDigestHeader(uri.PathAndQuery);
                request.AddParameter("Authorization", digestHeader, ParameterType.HttpHeader);
            }
        }
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var nonce = GetNonce();

            var url = client.BuildUri(request);

            var body = string.Empty;

            var param = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            if( param != null )
                body = param.Value.ToString();

            var hmacSig = GenerateSignature(nonce, url.ToString(), body, this.apiSecret);

            request.AddHeader("ACCESS_KEY", this.apiKey)
                .AddHeader("ACCESS_NONCE", nonce)
                .AddHeader("ACCESS_SIGNATURE", hmacSig);
        }
예제 #38
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var uri = client.BuildUri(request);
            var path = uri.AbsolutePath;

            if( path.EndsWith("/time") && path.Length <= 8 )
            {
                request.AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
                return;
            }
            string timestamp = null;
            if( useTimeApi )
            {
                var timeReq = new RestRequest("/time", Method.GET)
                    {
                        JsonSerializer = new JsonNetSerializer(jsonSettings)
                    };

                var timeResp = client.Execute<CoinbaseResponse<Time>>(timeReq);
                timestamp = timeResp.Data.Data.Epoch.ToString();
            }
            else
            {
                timestamp = GetCurrentUnixTimestampSeconds().ToString(CultureInfo.InvariantCulture);
            }

            var method = request.Method.ToString().ToUpper(CultureInfo.InvariantCulture);

            var body = string.Empty;

            var param = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            if (param != null && param?.Value?.ToString() != "null" && !string.IsNullOrWhiteSpace(param?.Value?.ToString()))
                body = param.Value.ToString();

            var hmacSig = GenerateSignature(timestamp, method, path, body, this.apiSecret);

            request.AddHeader("CB-ACCESS-KEY", this.apiKey)
                .AddHeader("CB-ACCESS-SIGN", hmacSig)
                .AddHeader("CB-ACCESS-TIMESTAMP", timestamp)
                .AddHeader("CB-VERSION", CoinbaseConstants.ApiVersionDate);
        }
        public void Authenticate( IRestClient client, IRestRequest request )
        {
            var uri = client.BuildUri( request );

            string method = AdaptMethod( request.Method );

            var tokens = m_context.CreateAuthenticatedTokens(uri, method);

            var authQueryParameters = CreateAuthQueryString( tokens );

            string url = uri.ToString();

            // manually set the resource url to work around RestSharp not letting you add query parameters
            // once you've added a body to the HTTP request
            bool hasQueryParameters = url.IndexOf( '?' ) != -1;

            if( hasQueryParameters ) {
                request.Resource = uri.PathAndQuery;
                request.Resource += "&" + authQueryParameters;
                request.Parameters.Clear();
            } else {
                request.Resource += "?" + authQueryParameters;
            }
        }
 /// <summary>
 /// Get the REST requests base address (for HTTP client)
 /// </summary>
 /// <param name="client">REST client</param>
 /// <returns>The base URL</returns>
 protected virtual Uri GetBaseAddress(IRestClient client)
 {
     return client.BuildUri(null, false);
 }
 /// <summary>
 /// Get the REST requests relative address (for HTTP request message)
 /// </summary>
 /// <param name="client">REST client</param>
 /// <param name="request">REST request</param>
 /// <returns>The relative request message URL</returns>
 protected virtual Uri GetMessageAddress(IRestClient client, IRestRequest request)
 {
     var fullUrl = client.BuildUri(request);
     var url = client.BuildUri(null, false).MakeRelativeUri(fullUrl);
     return url;
 }
예제 #42
0
        private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            string url = client.BuildUri(request)
                               .ToString();
            int queryStringStart = url.IndexOf('?');

            if (queryStringStart != -1)
            {
                url = url.Substring(0, queryStringStart);
            }

            OAuthWebQueryInfo oauth;
            string method = request.Method.ToString()
                                   .ToUpperInvariant();
            WebParameterCollection parameters = new WebParameterCollection();

            // include all GET and POST parameters before generating the signature
            // according to the RFC 5849 - The OAuth 1.0 Protocol
            // http://tools.ietf.org/html/rfc5849#section-3.4.1
            // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level,
            // or implement a seperate class for each OAuth version
            if (!request.AlwaysMultipartFormData && !request.Files.Any())
            {
                parameters.AddRange(
                    client.DefaultParameters
                          .Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)
                          .Select(p => new WebPair(p.Name, p.Value.ToString())));

                parameters.AddRange(
                    request.Parameters
                           .Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)
                           .Select(p => new WebPair(p.Name, p.Value.ToString())));
            }
            else
            {
                // if we are sending a multipart request, only the "oauth_" parameters should be included in the signature

                parameters.AddRange(
                    client.DefaultParameters
                          .Where(p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)
                                      && p.Name.StartsWith("oauth_"))
                          .Select(p => new WebPair(p.Name, p.Value.ToString())));

                parameters.AddRange(
                    request.Parameters
                           .Where(p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)
                                       && p.Name.StartsWith("oauth_"))
                           .Select(p => new WebPair(p.Name, p.Value.ToString())));
            }

            switch (this.Type)
            {
                case OAuthType.RequestToken:
                    workflow.RequestTokenUrl = url;
                    oauth = workflow.BuildRequestTokenInfo(method, parameters);
                    break;

                case OAuthType.AccessToken:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildAccessTokenInfo(method, parameters);
                    break;

                case OAuthType.ClientAuthentication:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildClientAuthAccessTokenInfo(method, parameters);
                    break;

                case OAuthType.ProtectedResource:
                    oauth = workflow.BuildProtectedResourceInfo(method, parameters, url);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }

            switch (this.ParameterHandling)
            {
                case OAuthParameterHandling.HttpAuthorizationHeader:
                    parameters.Add("oauth_signature", oauth.Signature);
                    request.AddHeader("Authorization", this.GetAuthorizationHeader(parameters));
                    break;

                case OAuthParameterHandling.UrlOrPostParameters:
                    parameters.Add("oauth_signature", oauth.Signature);
                    request.Parameters.AddRange(
                        parameters.Where(p => !p.Name.IsNullOrBlank() &&
                                              (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
                                  .Select(p => new Parameter
                                               {
                                                   Name = p.Name,
                                                   Value = HttpUtility.UrlDecode(p.Value),
                                                   Type = ParameterType.GetOrPost
                                               }));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
예제 #43
0
        protected String GetSessionId(IRestClient client, TransmissionSettings settings)
        {
            var request = new RestRequest();
            request.RequestFormat = DataFormat.Json;

            _logger.Debug("Url: {0} GetSessionId", client.BuildUri(request));
            var restResponse = client.Execute(request);

            if (restResponse.StatusCode == HttpStatusCode.MovedPermanently)
            {
                var uri = new Uri(restResponse.ResponseUri, (String)restResponse.GetHeaderValue("Location"));

                throw new DownloadClientException("Remote site redirected to " + uri);
            }

            // We expect the StatusCode = Conflict, coz that will provide us with a new session id.
            switch (restResponse.StatusCode)
            {
                case HttpStatusCode.Conflict:
                {
                    var sessionId = restResponse.Headers.SingleOrDefault(o => o.Name == "X-Transmission-Session-Id");

                    if (sessionId == null)
                    {
                        throw new DownloadClientException("Remote host did not return a Session Id.");
                    }

                    return (String)sessionId.Value;
                }
                case HttpStatusCode.Unauthorized:
                    throw new DownloadClientAuthenticationException("User authentication failed.");
            }

            restResponse.ValidateResponse(client);

            throw new DownloadClientException("Remote host did not return a Session Id.");
        }
예제 #44
0
        private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var url = client.BuildUri(request).ToString();
            var queryStringStart = url.IndexOf('?');
            if (queryStringStart != -1)
                url = url.Substring(0, queryStringStart);

            OAuthWebQueryInfo oauth;
            var method = request.Method.ToString().ToUpperInvariant();

            var parameters = new WebParameterCollection();

            // include all GET and POST parameters before generating the signature
            // according to the RFC 5849 - The OAuth 1.0 Protocol
            // http://tools.ietf.org/html/rfc5849#section-3.4.1
            // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level,
            // or implement a seperate class for each OAuth version
            foreach (var p in client.DefaultParameters.Where(p => p.Type == ParameterType.GetOrPost))
            {
                parameters.Add( new WebPair( p.Name, p.Value.ToString() ) );
            }
            foreach (var p in request.Parameters.Where(p => p.Type == ParameterType.GetOrPost))
            {
                parameters.Add(new WebPair(p.Name, p.Value.ToString()));
            }

            switch (Type)
            {
                case OAuthType.RequestToken:
                    workflow.RequestTokenUrl = url;
                    oauth = workflow.BuildRequestTokenInfo(method, parameters);
                    break;
                case OAuthType.AccessToken:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ClientAuthentication:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildClientAuthAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ProtectedResource:
                    oauth = workflow.BuildProtectedResourceInfo(method, parameters, url);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            switch (ParameterHandling)
            {
                case OAuthParameterHandling.HttpAuthorizationHeader:
                    parameters.Add("oauth_signature", oauth.Signature);
                    request.AddHeader("Authorization", GetAuthorizationHeader(parameters));
                    break;
                case OAuthParameterHandling.UrlOrPostParameters:
                    parameters.Add("oauth_signature", oauth.Signature);
                    foreach (var parameter in parameters.Where(parameter => !parameter.Name.IsNullOrBlank() && parameter.Name.StartsWith("oauth_")))
                    {
                        request.AddParameter(parameter.Name, HttpUtility.UrlDecode(parameter.Value));
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
예제 #45
0
        private UTorrentResponse ProcessRequest(IRestRequest request, IRestClient client)
        {
            _logger.Debug("Url: {0}", client.BuildUri(request));
            var clientResponse = client.Execute(request);

            if (clientResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                // Token has expired. If the settings were incorrect or the API is disabled we'd have gotten an error 400 during GetAuthToken
                _logger.Debug("uTorrent authentication token error.");

                _authToken = GetAuthToken(client);

                request.Parameters.First(v => v.Name == "token").Value = _authToken;
                clientResponse = client.Execute(request);
            }
            else if (clientResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new DownloadClientAuthenticationException("Failed to authenticate");
            }

            var uTorrentResult = clientResponse.Read<UTorrentResponse>(client);

            return uTorrentResult;
        }
        private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var url = client.BuildUri(request, false).ToString();
            OAuthWebQueryInfo oauth;
            var method = request.Method.ToString();
            var parameters = new WebParameterCollection();

            // include all GET and POST parameters before generating the signature
            // according to the RFC 5849 - The OAuth 1.0 Protocol
            // http://tools.ietf.org/html/rfc5849#section-3.4.1
            // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level,
            // or implement a seperate class for each OAuth version
            var useMultiPart = request.ContentCollectionMode == ContentCollectionMode.MultiPart
                               || (request.ContentCollectionMode == ContentCollectionMode.MultiPartForFileParameters
                                   && (client.DefaultParameters.GetFileParameters().Any() || request.Parameters.GetFileParameters().Any()));

            var requestParameters = client.MergeParameters(request).OtherParameters.AsEnumerable();
            var effectiveMethod = client.GetEffectiveHttpMethod(request);
            if (effectiveMethod == Method.GET)
            {
                requestParameters = requestParameters.Where(x => x.Type == ParameterType.GetOrPost || x.Type == ParameterType.QueryString);
                foreach (var p in requestParameters)
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Query));
                }
            }
            else if (!useMultiPart && effectiveMethod == Method.POST)
            {
                foreach (var p in requestParameters.Where(x => x.Type == ParameterType.QueryString))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Query));
                }
                foreach (var p in requestParameters.Where(x => x.Type == ParameterType.GetOrPost))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Post));
                }
            }
            else
            {
                // if we are sending a multipart request, only the "oauth_" parameters should be included in the signature
                foreach (var p in requestParameters.Where(p => p.Name.StartsWith("oauth_", StringComparison.Ordinal)))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Internal));
                }
            }

            switch (Type)
            {
                case OAuthType.RequestToken:
                    workflow.RequestTokenUrl = url;
                    oauth = workflow.BuildRequestTokenInfo(method, parameters);
                    break;
                case OAuthType.AccessToken:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ClientAuthentication:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildClientAuthAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ProtectedResource:
                    oauth = workflow.BuildProtectedResourceInfo(method, parameters, url);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            switch (ParameterHandling)
            {
                case OAuthParameterHandling.HttpAuthorizationHeader:
                    parameters.Add("oauth_signature", oauth.Signature, WebParameterType.Internal);
                    request.AddHeader("Authorization", GetAuthorizationHeader(parameters));
                    break;
                case OAuthParameterHandling.UrlOrPostParameters:
                    parameters.Add("oauth_signature", oauth.Signature, WebParameterType.Internal);
                    foreach (var parameter in parameters.Where(
                        parameter => !string.IsNullOrEmpty(parameter.Name)
                                     && (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_"))))
                    {
                        var v = parameter.Value;
                        v = Uri.UnescapeDataString(v.Replace('+', ' '));
                        request.AddOrUpdateParameter(parameter.Name, v);
                    }

                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
        /// <summary>
        /// Modifies the request to ensure that the authentication requirements are met.
        /// </summary>
        /// <param name="client">Client executing this request</param>
        /// <param name="request">Request to authenticate</param>
        /// <param name="credentials">The credentials used for the authentication</param>
        /// <returns>The task the authentication is performed on</returns>
        public Task PreAuthenticate(IRestClient client, IRestRequest request, ICredentials credentials)
        {
            if (credentials == null)
            {
                throw new InvalidOperationException("The credentials must be set using the IRestClient.Credential property.");
            }

            var cred = credentials.GetCredential(client.BuildUri(request, false), AuthenticationMethod);
            if (cred == null)
            {
                throw new InvalidOperationException($"No credentials provided for the {AuthenticationMethod} authentication type.");
            }

            request.Parameters.AddOrUpdate(new Parameter { Type = _parameterType, Name = _usernameKey, Value = cred.UserName, ValidateOnAdd = false });
            request.Parameters.AddOrUpdate(new Parameter { Type = _parameterType, Name = _passwordKey, Value = cred.Password, ValidateOnAdd = false });

#if USE_TASKEX
            return TaskEx.FromResult(0);
#else
            return Task.FromResult(0);
#endif
        }
예제 #48
0
        private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var url = client.BuildUri(request).ToString();

            OAuthWebQueryInfo oauth;
            var method = request.Method.ToString().ToUpperInvariant();

            var parameters = new WebParameterCollection();

            // for non-GET style requests make sure params are part of oauth signature
            if (request.Method != Method.GET && request.Method != Method.DELETE)
            {
                foreach (var p in request.Parameters.Where(p => p.Type == ParameterType.GetOrPost))
                {
                    parameters.Add(new WebPair(p.Name, p.Value.ToString()));
                }
            }

            switch (Type)
            {
                case OAuthType.RequestToken:
                    workflow.RequestTokenUrl = url;
                    oauth = workflow.BuildRequestTokenInfo(method, parameters);
                    break;
                case OAuthType.AccessToken:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ClientAuthentication:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildClientAuthAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ProtectedResource:
                    oauth = workflow.BuildProtectedResourceInfo(method, parameters, url);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            switch (ParameterHandling)
            {
                case OAuthParameterHandling.HttpAuthorizationHeader:
                    parameters.Add("oauth_signature", oauth.Signature);
                    request.AddHeader("Authorization", GetAuthorizationHeader(parameters));
                    break;
                case OAuthParameterHandling.UrlOrPostParameters:
                    parameters.Add("oauth_signature", HttpUtility.UrlDecode(oauth.Signature));
                    foreach (var parameter in parameters)
                    {
                        request.AddParameter(parameter.Name, parameter.Value);
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
예제 #49
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var url = client.BuildUri(request).ToString();

            // add body xauth arguments
            var arguments = new Dictionary<string, object>();
            if (string.IsNullOrWhiteSpace(Token))
            {
                arguments.Add("x_auth_username", Username);
                arguments.Add("x_auth_mode", "client_auth");
                arguments.Add("x_auth_password", Password);

                foreach (var item in arguments)
                {
                    request.AddParameter(item.Key, item.Value);
                }
            }
            else
            {
                foreach (var parameter in request.Parameters)
                {
                    arguments.Add(parameter.Name, parameter.Value);
                }
            }

            var nonce = OAuthTools.GetNonce();
            var signatureMethod = "HMAC-SHA1";
            var timeStamp = OAuthTools.GetTimestamp();
            var version = "1.0";

            var oauthArguments = new Dictionary<string, string>();
            oauthArguments.Add("oauth_signature_method", signatureMethod);
            oauthArguments.Add("oauth_nonce", nonce);
            oauthArguments.Add("oauth_consumer_key", ConsumerKey);
            oauthArguments.Add("oauth_timestamp", timeStamp);
            oauthArguments.Add("oauth_version", version);
            if (!string.IsNullOrWhiteSpace(Token))
            {
                oauthArguments.Add("oauth_token", Token);
            }

            var mergedArguments = new Dictionary<string, object>(arguments);
            foreach (var item in oauthArguments)
            {
                mergedArguments.Add(item.Key, item.Value);
            }

            mergedArguments = mergedArguments.OrderBy(i => i.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

            var signatureBase = String.Format("{0}&{1}&", Method.POST, OAuthTools.UrlEncodeRelaxed(url));
            foreach (var item in mergedArguments)
            {
                var encodedKey = OAuthTools.UrlEncodeRelaxed(item.Key);
                string encodedValue;
                if (item.Value != null)
                {
                    encodedValue = OAuthTools.UrlEncodeRelaxed(item.Value.ToString());
                }
                else
                {
                    encodedValue = string.Empty;
                }
                signatureBase += String.Format("{0}%3D{1}%26", encodedKey, encodedValue);
            }

            signatureBase = signatureBase.Substring(0, signatureBase.Length - 3);
            signatureBase = signatureBase.Replace("%40", "%2540"); // ugly hack for now...

            var signature = OAuthTools.GetSignature(signatureBase, ConsumerSecret, TokenSecret);

            // create authorization header
            var authHeader = "OAuth ";
            authHeader += string.Format("{0}=\"{1}\"", "oauth_signature", signature);

            foreach (var item in oauthArguments)
            {
                authHeader += string.Format(", {0}=\"{1}\"", item.Key, item.Value);
            }
            request.AddHeader("Authorization", authHeader);
        }
예제 #50
0
 public RestException(IRestResponse response, IRestClient restClient)
     : base(string.Format("REST request failed: [{0}] [{1}] at [{2}]", (int)response.StatusCode, response.Request.Method, restClient.BuildUri(response.Request)))
 {
     Response = response;
 }
예제 #51
0
        private String GetAuthToken(IRestClient client)
        {
            var request = new RestRequest();
            request.RequestFormat = DataFormat.Json;
            request.Resource = "/gui/token.html";

            _logger.Debug("Url: {0}", client.BuildUri(request));
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new DownloadClientAuthenticationException("Failed to authenticate");
            }

            response.ValidateResponse(client);

            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(response.Content);

            var authToken = xmlDoc.FirstChild.FirstChild.InnerText;

            _logger.Debug("uTorrent AuthToken={0}", authToken);

            return authToken;
        }