public static string GetAuthenticationMethodValue([NotNull] this IHttpResponseMessage response, AuthHeader header, [NotNull] string methodName)
 {
     return(GetAuthenticationHeaderInfo(response, header)
            .Where(x => string.Equals(x.Name, methodName, StringComparison.OrdinalIgnoreCase))
            .Select(x => x.RawValue)
            .SingleOrDefault());
 }
Ejemplo n.º 2
0
 public HttpClientResponse(Request request, IHttpResponseMessage response, HttpContent content, Exception error = null)
     : base(request)
 {
     Response = response;
     Content  = content;
     Error    = error;
 }
Ejemplo n.º 3
0
        internal void Connect()
        {
            IHttpResponseMessage response = null;

            try
            {
                var getTask = _webClient.GetAsync(_uri, _username, _password);
                getTask.Wait();
                response = getTask.Result;
            }
            catch (Exception)
            {
                throw new NeoServerUnavalaibleExpcetion(_uri, response.StatusCode.ToString());
            }

            if (!response.IsSuccessStatusCode)
            {
                throw new NeoServerUnavalaibleExpcetion(_uri, response.StatusCode.ToString());
            }

            var readTask = response.Content.ReadAsStringAsync();

            Task.WaitAll(readTask);
            var json            = readTask.Result;
            var serviceResponse = _webSerializer.Deserialize <ServiceRootResponse>(json);

            AssertVersion(serviceResponse);
        }
        /// <summary>
        /// Utility function that really initializes this response object from
        /// a HttpResponseMessage
        /// </summary>
        /// <param name="response">
        /// Response that will be used to initialize this response.
        /// </param>
        /// <returns>
        /// Task, because this function runs asynchronously
        /// </returns>
        /// <remarks>
        /// This override also deserializes the response
        /// </remarks>
        protected override async Task LoadResponse(IHttpResponseMessage response)
        {
            await base.LoadResponse(response);

            var handler = Client.GetHandler(ContentType);

            Data = (handler != null) ? handler.Deserialize <T>(this) : default(T);
        }
 /// <summary>
 /// Determines if the authentication module can handle the challenge sent with the response.
 /// </summary>
 /// <param name="client">The REST client the response is assigned to</param>
 /// <param name="request">The REST request the response is assigned to</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <param name="response">The response that returned the authentication challenge</param>
 /// <returns>true when the authenticator can handle the sent challenge</returns>
 public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     if (HasAuthorizationToken)
         return false;
     if (response.StatusCode == HttpStatusCode.NotFound)
         return true;
     return base.CanHandleChallenge(client, request, credentials, response);
 }
Ejemplo n.º 6
0
        public static IEnumerable <AuthHeaderInfo> GetAuthenticationHeaderInfo([NotNull] this IHttpResponseMessage response, AuthHeader header)
        {
            var headerName = header.ToAuthenticationHeaderName();
            IEnumerable <string> headerValues;

            if (!response.Headers.TryGetValues(headerName, out headerValues))
            {
                headerValues = _emptyHeaderValues;
            }
            return(headerValues
                   .SelectMany(ParseAuthenticationHeader)
                   .ToList());
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Utility function that really initializes this response object from
        /// a HttpResponseMessage
        /// </summary>
        /// <param name="response">Response that will be used to initialize this response.</param>
        /// <returns>Task, because this function runs asynchronously</returns>
        protected virtual async Task LoadResponse(IHttpResponseMessage response)
        {
            Headers = response.Headers;

            IsSuccess         = response.IsSuccessStatusCode;
            StatusCode        = response.StatusCode;
            StatusDescription = response.ReasonPhrase;

            var requestUri = Client.BuildUri(Request, false);

            ResponseUri = new Uri(requestUri, response.Headers.GetValue("Location", requestUri.ToString()));

            var content = response.Content;

            if (content == null)
            {
                RawBytes = new byte[0];
            }
            else
            {
                var contentType = content.Headers.GetValue("Content-Type");
                if (string.IsNullOrEmpty(contentType))
                {
                    ContentType = string.Empty;
                }
                else
                {
                    var semicolonPos = contentType.IndexOf(';');
                    if (semicolonPos != -1)
                    {
                        contentType = contentType.Substring(0, semicolonPos);
                    }

                    ContentType = contentType.Trim();
                }

                var data = await content.ReadAsByteArrayAsync();

                IEnumerable <string> contentEncodings;
                if (content.Headers.TryGetValues("Content-Encoding", out contentEncodings))
                {
                    var encoding = Client.GetEncoding(contentEncodings);
                    if (encoding != null)
                    {
                        data = encoding.Decode(data);
                    }
                }

                RawBytes = data;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Utility function that really initializes this response object from
        /// a HttpResponseMessage
        /// </summary>
        /// <param name="response">
        /// Response that will be used to initialize this response.
        /// </param>
        /// <param name="ct">The cancellation token</param>
        /// <returns>
        /// Task, because this function runs asynchronously
        /// </returns>
        /// <remarks>
        /// This override also deserializes the response
        /// </remarks>
        protected override async Task LoadResponse(IHttpResponseMessage response, CancellationToken ct)
        {
            await base.LoadResponse(response, ct).ConfigureAwait(false);

            if (RawBytes != null)
            {
                var handler = Client.GetHandler(ContentType);
                Data = (handler != null) ? handler.Deserialize <T>(this) : default(T);
            }
            else
            {
                Data = default(T);
            }
        }
Ejemplo n.º 9
0
        internal void Connect()
        {
            IHttpResponseMessage response = null;

            try
            {
                response = _webClient.GetAsync(_uri).Result;
            }
            catch (Exception)
            {
                throw new NeoServerUnavalaibleExpcetion(_uri);
            }
            var json            = response.Content.ReadAsStringAsync().Result;
            var serviceResponse = _webSerializer.Deserialize <ServiceRootResponse>(json);

            AssertVersion(serviceResponse);
        }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No credentials defined?
            if (credentials == null)
            {
                return(false);
            }

            // No challenge header found?
            var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);

            if (authModeInfo == null)
            {
                return(false);
            }

            // Search for credential for request URI
            var responseUri = client.GetRequestUri(request, response);
            var credential  = credentials.GetCredential(responseUri, AuthenticationMethod);

            if (credential == null)
            {
                return(false);
            }

            // Did we already try to use the found credentials?
            if (ReferenceEquals(credential, _authCredential))
            {
                // Yes, so we don't retry the authentication.
                return(false);
            }

            return(true);
        }
        /// <inheritdoc/>
        public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // Get authentication header using the method specified by <code>_tokenType</code> or <code>OAuth</code>
            var authHeaderInfo = response
                .GetAuthenticationHeaderInfo(AuthHeader.Www)
                .FirstOrDefault(
                    x => string.Equals(x.Name, _tokenType, StringComparison.OrdinalIgnoreCase)
                         || string.Equals(x.Name, "OAuth", StringComparison.OrdinalIgnoreCase));
            if (authHeaderInfo == null)
                return false;

            // Check for WWW-Authenticate when status code is 401 (Unauthorized)
            if (response.StatusCode == HttpStatusCode.Unauthorized)
                return authHeaderInfo.Values["error"].Any(x => string.Equals(x, "invalid_token"));

            // Not a 400 (Bad Request)? Cannot handle challenge.
            if (response.StatusCode != HttpStatusCode.BadRequest)
                return false;

            // Check for Facebooks broken WWW-Authenticate
            var isFacebook = authHeaderInfo.Values[string.Empty].Any(x => x.Contains("Facebook"));
            if (!isFacebook)
                return false;
            if (!authHeaderInfo.Values[string.Empty].Any(x => x.Equals("invalid_token", StringComparison.OrdinalIgnoreCase)))
                return false;

            if (!base.CanHandleChallenge(client, request, credentials, response))
                return false;

            return true;
        }
Ejemplo n.º 12
0
 private IReleaseStorage WebReleaseStorage(IHttpResponseMessage httpResponse)
 {
     _httpClient.GetAsync(_config.FeedUri).Returns(httpResponse);
     return(WebReleaseStorage());
 }
        public static Uri GetRequestUri([CanBeNull] this IHttpClient client, [NotNull] IHttpRequestMessage request, [NotNull] IHttpResponseMessage response)
        {
            var requestUri = client.GetRequestUri(request);
            IEnumerable <string> locationValues;

            if (!response.Headers.TryGetValues("Location", out locationValues))
            {
                return(requestUri);
            }

            var location = locationValues.FirstOrDefault();

            if (string.IsNullOrWhiteSpace(location))
            {
                return(requestUri);
            }

            return(new Uri(requestUri, location));
        }
        /// <summary>
        /// Will be called when the authentication failed
        /// </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>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            return Task.Factory.StartNew(() =>
            {
                if (!CanHandleChallenge(client, request, credentials, response))
                    throw new InvalidOperationException();

                var responseUri = client.GetRequestUri(request, response);
                _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod);
                var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);
                ParseResponseHeader(authModeInfo);
            });
        }
 /// <summary>
 /// Will be called when the authentication failed
 /// </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>
 /// <param name="response">Response of the failed request</param>
 /// <returns>Task where the handler for a failed authentication gets executed</returns>
 public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     throw new NotSupportedException();
 }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No refresh token? Cannot handle challenge
            if (string.IsNullOrEmpty(Client.RefreshToken))
            {
                return(false);
            }

            var currentChallenge = DateTimeOffset.UtcNow;

            if (_lastChallenge.HasValue)
            {
                var safetyMargin = TimeSpan.FromSeconds(60);
                if (currentChallenge < _lastChallenge.Value + safetyMargin)
                {
                    return(false);
                }
            }
            _lastChallenge = currentChallenge;
            return(true);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Will be called when the authentication failed
        /// </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>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            var authenticator = response
                                .GetAuthenticationHeaderInfo(Header)
                                .Where(x => _authenticators.ContainsKey(x.Name))
                                .Select(x => _authenticators[x.Name])
                                .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response))
                                .OrderByDescending(x => x.Security)
                                .Select(x => x.Authenticator)
                                .First();

            return(authenticator.HandleChallenge(client, request, credentials, response));
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Determines if the authentication module can handle the challenge sent with the response.
 /// </summary>
 /// <param name="client">The HTTP client the response is assigned to</param>
 /// <param name="request">The HTTP request the response is assigned to</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <param name="response">The response that returned the authentication challenge</param>
 /// <returns>true when the authenticator can handle the sent challenge</returns>
 public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     return(false);
 }
 /// <summary>
 /// Will be called when the authentication failed
 /// </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>
 /// <param name="response">Response of the failed request</param>
 /// <returns>Task where the handler for a failed authentication gets executed</returns>
 public async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     var authenticator = response
         .GetAuthenticationHeaderInfo(Header)
         .Where(x => _authenticators.ContainsKey(x.Name))
         .Select(x => _authenticators[x.Name])
         .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response))
         .OrderByDescending(x => x.Security)
         .Select(x => x.Authenticator)
         .First();
     await authenticator.HandleChallenge(client, request, credentials, response);
 }
 /// <summary>
 /// Determines if the authentication module can handle the challenge sent with the response.
 /// </summary>
 /// <param name="client">The REST client the response is assigned to</param>
 /// <param name="request">The REST request the response is assigned to</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <param name="response">The response that returned the authentication challenge</param>
 /// <returns>true when the authenticator can handle the sent challenge</returns>
 public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     return response
         .GetAuthenticationHeaderInfo(Header)
         .Where(x => _authenticators.ContainsKey(x.Name))
         .Select(x => _authenticators[x.Name])
         .Where(x => x.Authenticator.CanHandleChallenge(client, request, credentials, response))
         .OrderByDescending(x => x.Security)
         .Select(x => x.Authenticator)
         .Any();
 }
 public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response) => false;
Ejemplo n.º 22
0
 private IDownloadableFile DownloadableFile(string uri, IHttpResponseMessage httpResponse)
 {
     _httpClient.GetAsync(uri).Returns(httpResponse);
     return(DownloadableFile());
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Will be called when the authentication failed
 /// </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>
 /// <param name="response">Response of the failed request</param>
 /// <returns>Task where the handler for a failed authentication gets executed</returns>
 public virtual Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     throw new NotSupportedException();
 }
 /// <summary>
 /// Will be called when the authentication failed
 /// </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>
 /// <param name="response">Response of the failed request</param>
 /// <returns>Task where the handler for a failed authentication gets executed</returns>
 public virtual async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     if (!CanHandleChallenge(client, request, credentials, response))
     {
         throw new InvalidOperationException();
     }
     await Client.GetCurrentToken(forceUpdate : true);
 }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No credentials defined?
            if (credentials == null)
                return false;

            // No challenge header found?
            var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);
            if (authModeInfo == null)
                return false;

            // Search for credential for request URI
            var responseUri = client.GetRequestUri(request, response);
            var credential = credentials.GetCredential(responseUri, AuthenticationMethod);
            if (credential == null)
                return false;

            // Did we already try to use the found credentials?
            if (ReferenceEquals(credential, _authCredential))
            {
                // Yes, so we don't retry the authentication.
                return false;
            }

            return true;
        }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            if (HasAuthorizationToken)
            {
                return(false);
            }

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(true);
            }

            return(base.CanHandleChallenge(client, request, credentials, response));
        }
Ejemplo n.º 27
0
 public System.Threading.Tasks.Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 28
0
 public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     throw new NotImplementedException();
 }
 internal static LuisResponse AsLuisResponse(this IHttpResponseMessage responseMessage)
 {
     return(JsonConvert.DeserializeObject <LuisResponse>(responseMessage.Content));
 }
Ejemplo n.º 30
0
        /// <inheritdoc/>
        public override bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // Get authentication header using the method specified by <code>_tokenType</code> or <code>OAuth</code>
            var authHeaderInfo = response
                                 .GetAuthenticationHeaderInfo(AuthHeader.Www)
                                 .FirstOrDefault(
                x => string.Equals(x.Name, _tokenType, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(x.Name, "OAuth", StringComparison.OrdinalIgnoreCase));

            if (authHeaderInfo == null)
            {
                return(false);
            }

            // Check for WWW-Authenticate when status code is 401 (Unauthorized)
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                return(authHeaderInfo.Values["error"].Any(x => string.Equals(x, "invalid_token")));
            }

            // Not a 400 (Bad Request)? Cannot handle challenge.
            if (response.StatusCode != HttpStatusCode.BadRequest)
            {
                return(false);
            }

            // Check for Facebooks broken WWW-Authenticate
            var isFacebook = authHeaderInfo.Values[string.Empty].Any(x => x.Contains("Facebook"));

            if (!isFacebook)
            {
                return(false);
            }
            if (!authHeaderInfo.Values[string.Empty].Any(x => x.Equals("invalid_token", StringComparison.OrdinalIgnoreCase)))
            {
                return(false);
            }

            if (!base.CanHandleChallenge(client, request, credentials, response))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Create a <see cref="IRestResponse"/> from a <see cref="IRestClient"/>, <see cref="IRestRequest"/> and a <see cref="IHttpResponseMessage"/>.
        /// </summary>
        /// <typeparam name="T">The type to instantiate the response for.</typeparam>
        /// <param name="client">The <see cref="IRestClient"/> used to create a <see cref="IRestResponse"/></param>
        /// <param name="request">The <see cref="IRestRequest"/> used to create a <see cref="IRestResponse"/></param>
        /// <param name="responseMessage">The <see cref="IHttpResponseMessage"/> used to create a <see cref="IRestResponse"/></param>
        /// <param name="ct">The cancellation token</param>
        /// <returns>The new <see cref="IRestResponse"/></returns>
        public static async Task <IRestResponse <T> > CreateResponse <T>(IRestClient client, IRestRequest request, IHttpResponseMessage responseMessage, CancellationToken ct)
        {
            var response = new RestResponse <T>(client, request);
            await response.LoadResponse(responseMessage, ct);

            return(response);
        }
        /// <summary>
        /// Will be called when the authentication failed
        /// </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>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            return Task.Factory.StartNew(() =>
            {
                if (!CanHandleChallenge(client, request, credentials, response))
                {
                    throw new InvalidOperationException();
                }

                var responseUri = client.GetRequestUri(request, response);
                _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod);
                _authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_authCredential.UserName}:{_authCredential.Password}"));
            });
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Will be called when the authentication failed
        /// </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>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            if (!CanHandleChallenge(client, request, credentials, response))
            {
                throw new InvalidOperationException();
            }

            var responseUri = client.GetRequestUri(request, response);

            _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod);
            _authToken      = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_authCredential.UserName}:{_authCredential.Password}"));

#if ASYNC_PCL
            return(Task.FromResult(0));
#else
            return(new Task(() => { }));
#endif
        }
 /// <summary>
 /// Will be called when the authentication failed
 /// </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>
 /// <param name="response">Response of the failed request</param>
 /// <returns>Task where the handler for a failed authentication gets executed</returns>
 public virtual async Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     if (!CanHandleChallenge(client, request, credentials, response))
         throw new InvalidOperationException();
     await Client.GetCurrentToken(forceUpdate: true);
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Utility function that really initializes this response object from
        /// a HttpResponseMessage
        /// </summary>
        /// <param name="response">Response that will be used to initialize this response.</param>
        /// <param name="ct">The cancellation token</param>
        /// <returns>Task, because this function runs asynchronously</returns>
        protected virtual async Task LoadResponse(IHttpResponseMessage response, CancellationToken ct)
        {
            Headers = response.Headers;

            IsSuccess         = response.IsSuccessStatusCode;
            StatusCode        = response.StatusCode;
            StatusDescription = response.ReasonPhrase;

            var requestUri = Client.BuildUri(Request, false);

            ResponseUri = new Uri(requestUri, response.Headers.GetValue("Location", requestUri.ToString()));

            Cookies = response.Cookies?.GetCookies(ResponseUri);

            var content = response.Content;

            if (content == null)
            {
                RawBytes = new byte[0];
            }
            else
            {
                var contentType = content.Headers.GetValue("Content-Type");
                if (string.IsNullOrEmpty(contentType))
                {
                    ContentType = string.Empty;
                }
                else
                {
                    var semicolonPos = contentType.IndexOf(';');
                    if (semicolonPos != -1)
                    {
                        contentType = contentType.Substring(0, semicolonPos);
                    }

                    ContentType = contentType.Trim();
                }

                var responseWriter = Request.ResponseWriterAsync;
                if (responseWriter != null)
                {
                    if (response.Content != null)
                    {
                        var responseStream = await response.Content.ReadAsStreamAsync();

                        if (responseStream != null)
                        {
                            var encoding = response.Content.GetEncoding(Client);
                            if (encoding != null)
                            {
                                responseStream = encoding.DecodeStream(responseStream);
                            }
                            await responseWriter(responseStream, ct);
                        }
                    }
                }
                else
                {
                    var data = await content.ReadAsByteArrayAsync();

                    var encoding = content.GetEncoding(Client);
                    if (encoding != null)
                    {
                        data = encoding.Decode(data);
                    }

                    RawBytes = data;
                }
            }
        }
Ejemplo n.º 36
0
        public static async Task <HttpClientResponse> Create(HttpClientRequest request, IHttpResponseMessage response)
        {
            var content = await response.Content.GetContent().ConfigureAwait(false);

            return(new HttpClientResponse(request, response, content));
        }
Ejemplo n.º 37
0
 public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response)
 {
     return false;
 }
Ejemplo n.º 38
0
 public bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response)
 {
     return(false);
 }
        /// <summary>
        /// Will be called when the authentication failed
        /// </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>
        /// <param name="response">Response of the failed request</param>
        /// <returns>Task where the handler for a failed authentication gets executed</returns>
        public Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            if (!CanHandleChallenge(client, request, credentials, response))
            {
                throw new InvalidOperationException();
            }

            var responseUri = client.GetRequestUri(request, response);

            _authCredential = credentials.GetCredential(responseUri, AuthenticationMethod);
            var authModeInfo = response.GetAuthenticationMethodValue(_authHeader, AuthenticationMethod);

            ParseResponseHeader(authModeInfo);

#if USE_TASKEX
            return(TaskEx.FromResult(0));
#else
            return(Task.FromResult(0));
#endif
        }
 /// <summary>
 /// Determines if the authentication module can handle the challenge sent with the response.
 /// </summary>
 /// <param name="client">The REST client the response is assigned to</param>
 /// <param name="request">The REST request the response is assigned to</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <param name="response">The response that returned the authentication challenge</param>
 /// <returns>true when the authenticator can handle the sent challenge</returns>
 public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     return !string.IsNullOrEmpty(Client.RefreshToken);
 }
 /// <summary>
 /// Determines if the authentication module can handle the challenge sent with the response.
 /// </summary>
 /// <param name="client">The HTTP client the response is assigned to</param>
 /// <param name="request">The HTTP request the response is assigned to</param>
 /// <param name="credentials">The credentials to be used for the authentication</param>
 /// <param name="response">The response that returned the authentication challenge</param>
 /// <returns>true when the authenticator can handle the sent challenge</returns>
 public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
 {
     return false;
 }
        /// <summary>
        /// Determines if the authentication module can handle the challenge sent with the response.
        /// </summary>
        /// <param name="client">The REST client the response is assigned to</param>
        /// <param name="request">The REST request the response is assigned to</param>
        /// <param name="credentials">The credentials to be used for the authentication</param>
        /// <param name="response">The response that returned the authentication challenge</param>
        /// <returns>true when the authenticator can handle the sent challenge</returns>
        public virtual bool CanHandleChallenge(IHttpClient client, IHttpRequestMessage request, ICredentials credentials, IHttpResponseMessage response)
        {
            // No refresh token? Cannot handle challenge
            if (string.IsNullOrEmpty(Client.RefreshToken))
                return false;

            var currentChallenge = DateTimeOffset.UtcNow;
            if (_lastChallenge.HasValue)
            {
                var safetyMargin = TimeSpan.FromSeconds(60);
                if (currentChallenge < _lastChallenge.Value + safetyMargin)
                    return false;
            }
            _lastChallenge = currentChallenge;
            return true;
        }
Ejemplo n.º 43
0
 public System.Threading.Tasks.Task HandleChallenge(IHttpClient client, IHttpRequestMessage request, System.Net.ICredentials credentials, IHttpResponseMessage response)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Create a <see cref="IRestResponse"/> from a <see cref="IRestClient"/>, <see cref="IRestRequest"/> and a <see cref="IHttpResponseMessage"/>.
        /// </summary>
        /// <param name="client">The <see cref="IRestClient"/> used to create a <see cref="IRestResponse"/></param>
        /// <param name="request">The <see cref="IRestRequest"/> used to create a <see cref="IRestResponse"/></param>
        /// <param name="responseMessage">The <see cref="IHttpResponseMessage"/> used to create a <see cref="IRestResponse"/></param>
        /// <returns>The new <see cref="IRestResponse"/></returns>
        public static async Task <IRestResponse> CreateResponse(IRestClient client, IRestRequest request, IHttpResponseMessage responseMessage)
        {
            var response = new RestResponse(client, request);
            await response.LoadResponse(responseMessage);

            return(response);
        }