Exemple #1
0
        private string GetAuthenticationHeader(RestSharp.IRestClient client, RestSharp.IRestRequest request)
        {
            string requestContentBase64String = string.Empty;

            //Calculate UNIX time
            DateTime epochStart       = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan timeSpan         = DateTime.UtcNow - epochStart;
            string   requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();

            //create random nonce for each request
            string nonce = Guid.NewGuid().ToString("N");

            // URLEncode the request URI
            var requestUri = HttpUtility.UrlEncode(client.BuildUri(request).AbsoluteUri.ToLower());

            //Creating the raw signature string
            string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", _srApiKey, request.Method, requestUri, requestTimeStamp, nonce, requestContentBase64String);

            var secretKeyByteArray = Convert.FromBase64String(_srApiSecret);

            byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);

            using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
            {
                byte[] signatureBytes = hmac.ComputeHash(signature);
                string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
                //Setting the values in the Authorization header using custom scheme (amx)
                return("amx " +
                       string.Format("{0}:{1}:{2}:{3}", _srApiKey, requestSignatureBase64String, nonce, requestTimeStamp));
            }
        }
Exemple #2
0
 public void Authenticate(RSharp.IRestClient client, RSharp.IRestRequest request)
 {
     if (!request.Parameters.Any(p => "Authorization".Equals(p.Name, StringComparison.OrdinalIgnoreCase)))
     {
         request.AddParameter("Authorization", authHeader, RSharp.ParameterType.HttpHeader);
     }
 }
Exemple #3
0
        private void ValidateRequest(RestSharp.IRestClient client,
                                     Data.RestRequest requestDetails)
        {
            // Client cannot be null.
            if (client.BaseUrl == null || string.IsNullOrWhiteSpace(client.BaseUrl.AbsoluteUri))
            {
                throw new ArgumentException("Host address is not set: "
                                            + "Please pass a valid host address.");
            }

            if (requestDetails == null)
            {
                throw new System.ArgumentException("HTTP request details not supplied.");
            }

            if (requestDetails.HttpMethod == Data.RestRequest.Method.NotSet)
            {
                throw new System.ArgumentException(
                          "HTTP request method is not set (eg \"GET\", \"POST\").");
            }

            if (string.IsNullOrWhiteSpace(requestDetails.Resource))
            {
                throw new System.ArgumentException("Relative URL of resource is not set.");
            }
        }
Exemple #4
0
 /// <summary>
 /// Adds the API token key to the REST request header
 /// </summary>
 public void Authenticate(RestSharp.IRestClient client, RestSharp.IRestRequest request)
 {
     if (!request.Parameters.Any(p => p.Name.Equals("X-TOKEN", StringComparison.OrdinalIgnoreCase)))
     {
         var token = string.Format("{0}", _apiToken);
         request.AddParameter("X-TOKEN", token, ParameterType.HttpHeader);
     }
 }
        public FetchCloudEngagementsJob(IDbConnection db, IRestClient restClient,
                                        IIdentityProvider identityProvider, ILogger <FetchCloudEngagementsJob> logger,
                                        IMemoryCache cache, IOptionsMonitor <AppConfig> configMonitor,
                                        ICloudHandler cloudHandler)
        {
            _restClient       = restClient;
            _db               = db;
            _identityProvider = identityProvider;
            _logger           = logger;
            _cache            = cache;
            _config           = configMonitor.CurrentValue;
            _cloudHandler     = cloudHandler;

            logger.LogDebug("FCEJ: init successful, dependencies processed.");
        }
        /// <summary>
        /// Enumerates the client's cookie container looking for the cookie requested and calls the action when the cookie is found
        /// </summary>
        /// <param name="client">The client to be processed against</param>
        /// <param name="cookieName">The name of the cookie to locate</param>
        /// <param name="foundCookie">The action to occur if the cookie is found</param>
        /// <returns>Whether or not the cookie is found</returns>
        private static bool FindCookie(RestSharp.IRestClient client, string cookieName, Action <Cookie> foundCookie)
        {
            bool result = false;

            if (client != null && client.CookieContainer != null || client.CookieContainer.GetCookies(client.BaseUrl).Count >= 0)
            {
                foreach (Cookie cookie in client.CookieContainer.GetCookies(client.BaseUrl))
                {
                    if (string.Equals(cookie.Name, cookieName) == true)
                    {
                        if (foundCookie != null)
                        {
                            foundCookie(cookie);
                        }

                        result = true;
                        break;
                    }
                }
            }

            return(result);
        }
Exemple #7
0
 public RegisterRepo()
 {
     _client = new RestClient(BaseUrl);
     request = new RestRequest("api/register", Method.POST);
 }
 public EbBaseService(RestSharp.IRestClient _rest)
 {
     this.RestClient = _rest as RestClient;
 }
            public void Authenticate(RestSharp.IRestClient client, IRestRequest request)
            {
                client.UserAgent = UserAgent;

                request.AddHeader("Authorization", ApiToken);
            }
Exemple #10
0
 public RestClient(IResponseDeserializer deserializer, RestSharp.IRestClient restClient)
 {
     _deserializer = deserializer;
     _restClient   = restClient;
 }
Exemple #11
0
        public Data.RestResponse Execute(string baseAddress, Data.RestRequest requestDetails)
        {
            this.BaseUrlString = baseAddress;
            RestSharp.IRestClient client = this.Client;

            // We're using RestSharp to execute HTTP requests.  RestSharp copes with trailing "/"
            //  on BaseUrl and leading "/" on Resource, whether one or both of the "/" are present
            //  or absent.

            ValidateRequest(client, requestDetails);

            if (requestDetails.TransactionId == null)
            {
                requestDetails.TransactionId = Convert.ToInt64(DateTimeHelper.CurrentUnixTimeMillis());
            }

            client.FollowRedirects = requestDetails.FollowRedirect;

            RestSharp.RestRequest request = BuildRequest(requestDetails);

            if (LOG.IsDebugEnabled)
            {
                try
                {
                    LOG.Info("Http Request : {0} {1}",
                             request.Method, client.BuildUri(request).AbsoluteUri);
                }
                catch (Exception e)
                {
                    LOG.Error(e, "Exception in debug : {0}", e.Message);
                }

                // Request Header
                LogRequestHeaders(request);

                // Request Body
                if (IsEntityEnclosingMethod(request.Method))
                {
                    try
                    {
                        Parameter body = request.Parameters
                                         .Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
                        LOG.Debug("Http Request Body : {0}", body.Value);
                    }
                    catch (IOException e)
                    {
                        LOG.Error(e, "Error in reading request body in debug : {0}", e.Message);
                    }
                }
            }

            // Prepare Response
            Data.RestResponse responseDetails = new Data.RestResponse();
            responseDetails.TransactionId = requestDetails.TransactionId;
            responseDetails.Resource      = requestDetails.Resource;
            try
            {
                IRestResponse response = client.Execute(request);

                foreach (RestSharp.Parameter responseHeader in response.Headers)
                {
                    responseDetails.addHeader(responseHeader.Name, responseHeader.Value.ToString());
                }

                responseDetails.StatusCode = (int)response.StatusCode;
                responseDetails.StatusText = response.StatusDescription;
                // The Java byte data type is actually a signed byte, equivalent to sbyte in .NET.
                //  Data.RestResponse is a direct port of the Java class so it uses
                //  the sbyte data type.  The strange conversion from byte[] to sbyte[] was from
                //  the answer to Stackoverflow question http://stackoverflow.com/questions/25759878/convert-byte-to-sbyte
                // TODO: Check RestFixture code to see whether Data.RestResponse.RawBody can be converted to byte[].
                responseDetails.RawBody = response.RawBytes;

                // Debug
                if (LOG.IsDebugEnabled)
                {
                    // Not necessarily the same as the request URI.  The response URI is the URI
                    //  that finally responds to the request, after any redirects.
                    LOG.Debug("Http Request Path : {0}", response.ResponseUri);
                    LogRequestHeaders(request);
                    // Apache HttpClient.HttpMethod.getStatusLine() returns the HTTP response
                    //  status line.  Can't do this with RestSharp as it cannot retrieve the
                    //  protocol version which is at the start of the status line.  So just log
                    //  the status code and description.
                    // Looks like they added ProtocolVersion to RestSharp in issue 795 (commit
                    //  52c18a8) but it's only available in the FRAMEWORK builds.
                    LOG.Debug("Http Response Status : {0} {1}",
                              (int)response.StatusCode, response.StatusDescription);
                    LOG.Debug("Http Response Body : {0}", response.Content);
                }

                if (IsResponseError(response))
                {
                    LOG.Error(response.ErrorException, response.ErrorMessage);
                    string message = "Http call failed";
                    if (!string.IsNullOrWhiteSpace(response.ErrorMessage))
                    {
                        message = response.ErrorMessage.Trim();
                    }
                    throw new System.InvalidOperationException(message, response.ErrorException);
                }
            }
            catch (Exception e)
            {
                string message = "Http call failed";
                throw new System.InvalidOperationException(message, e);
            }

            LOG.Debug("response: {0}", responseDetails);
            return(responseDetails);
        }
Exemple #12
0
 /// <summary>
 ///
 /// Initializes a new instance of the Client.
 /// </summary>
 public RestClientImpl()
 {
     this.Client = new RestSharp.RestClient();
 }