Beispiel #1
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState, string cloudAudience)
        {
            IHttpClient request = PlatformPlugin.HttpClientFactory.Create(wsTrustAddress.Uri.AbsoluteUri, callState);

            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            if (string.IsNullOrEmpty(cloudAudience))
            {
                cloudAudience = defaultAppliesTo;
            }

            StringBuilder messageBuilder = BuildMessage(cloudAudience, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters        = new StringRequestParameters(messageBuilder);
                request.Headers["SOAPAction"] = soapAction;
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);

                wstResponse = WsTrustResponse.CreateFromResponse(EncodingHelper.GenerateStreamFromString(response.ResponseString), wsTrustAddress.Version);
            }
            catch (HttpRequestWrapperException ex)
            {
                string errorMessage;

                try
                {
                    using (Stream stream = EncodingHelper.GenerateStreamFromString(ex.WebResponse.ResponseString))
                    {
                        XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(stream);
                        errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                    }
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
Beispiel #2
0
        /// <summary>
        /// Execute request and returns entityResponse - ASYNC.
        /// </summary>
        /// <param name="httpWebRequest">Http web request.</param>
        /// <returns></returns>
        protected async Task <IHttpWebResponse> ExecuteRequestAsync(IHttpWebRequest httpWebRequest)
        {
            this.PreExecuteRequest(httpWebRequest);
            IHttpWebResponse httpWebResponse = await httpWebRequest.GetResponseAsync();

            this.ProcessHttpWebResponseInternal(httpWebResponse);
            return(httpWebResponse);
        }
Beispiel #3
0
        /// <summary>
        /// Execute request and returns entityResponse.
        /// </summary>
        /// <param name="httpWebRequest">Http web request.</param>
        /// <returns></returns>
        protected IHttpWebResponse ExecuteRequest(IHttpWebRequest httpWebRequest)
        {
            this.PreExecuteRequest(httpWebRequest);
            IHttpWebResponse httpWebResponse = httpWebRequest.GetResponse();

            this.ProcessHttpWebResponseInternal(httpWebResponse);
            return(httpWebResponse);
        }
Beispiel #4
0
 /// <summary>
 /// Execute POST request.
 /// </summary>
 /// <param name="content"></param>
 /// <returns></returns>
 protected IHttpWebResponse ExecuteRequest(string content)
 {
     using (IHttpWebRequest httpWebRequest = HttpWebRequest.Patch(this.RestUrl, content))
     {
         IHttpWebResponse httpWebResponse = this.ExecuteRequest(httpWebRequest);
         return(httpWebResponse);
     }
 }
 /// <summary>
 /// Reads the full stream from the response and returns the content as stream,
 /// using the correct encoding.
 /// </summary>
 /// <param name="response">Web response from request to Solr</param>
 private string ReadResponseToString(IHttpWebResponse response)
 {
     using (var responseStream = response.GetResponseStream())
         using (var reader = new StreamReader(responseStream, TryGetEncoding(response)))
         {
             return(reader.ReadToEnd());
         }
 }
 private Encoding TryGetEncoding(IHttpWebResponse response)
 {
     try {
         return(Encoding.GetEncoding(response.CharacterSet));
     } catch {
         return(Encoding.UTF8);
     }
 }
 private async Task <string> ReadResponseToStringAsync(IHttpWebResponse response)
 {
     using (var responseStream = response.GetResponseStream())
         using (var reader = new StreamReader(responseStream, TryGetEncoding(response)))
         {
             return(await reader.ReadToEndAsync());
         }
 }
 private bool isDeviceAuthChallenge(string endpointType, IHttpWebResponse response, bool respondToDeviceAuthChallenge)
 {
     return(PlatformPlugin.DeviceAuthHelper.CanHandleDeviceAuthChallenge &&
            respondToDeviceAuthChallenge &&
            (response.Headers.ContainsKey(WwwAuthenticateHeader) &&
             response.Headers[WwwAuthenticateHeader].StartsWith(PKeyAuthName, StringComparison.CurrentCulture)) &&
            endpointType.Equals(ClientMetricsEndpointType.Token));
 }
Beispiel #9
0
        /// <summary>
        /// Execute in async fashion.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        internal async Task <T> ExecuteAsync <T>()
        {
            IHttpWebResponse response = await this.ExecuteRequestAsync(this.PatchContent);

            return(this.Deserialize <T>(
                       response,
                       this.DeserializationType));
        }
Beispiel #10
0
 private bool isDeviceAuthChallenge(IHttpWebResponse response, bool respondToDeviceAuthChallenge)
 {
     return(PlatformPlugin.DeviceAuthHelper.CanHandleDeviceAuthChallenge &&
            respondToDeviceAuthChallenge &&
            response?.Headers != null &&
            response.Headers.ContainsKey(WwwAuthenticateHeader) &&
            response.Headers[WwwAuthenticateHeader].StartsWith(PKeyAuthName, StringComparison.OrdinalIgnoreCase));
 }
Beispiel #11
0
 /// <summary>
 /// Attempts to deflate response stream if compressed in any way.
 /// </summary>
 /// <see cref="http://west-wind.com/weblog/posts/102969.aspx"/>
 /// <param name="response">Web response from request to Solr</param>
 /// <returns></returns>
 private string UncompressResponse(IHttpWebResponse response)
 {
     using (var responseStream = response.GetResponseStream())
         using (var compressedStream = GetWrappedCompressionStream(response, responseStream)) {
             var reader = new StreamReader(compressedStream, TryGetEncoding(response));
             return(reader.ReadToEnd());
         }
 }
Beispiel #12
0
        /// <summary>
        /// Execute and returns result.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        internal T Execute <T>()
        {
            IHttpWebResponse response = this.ExecuteRequest(this.PatchContent);

            return(this.Deserialize <T>(
                       response,
                       this.DeserializationType));
        }
Beispiel #13
0
 private static void SetKeepAliveHeaders(HttpWebRequest request, IHttpWebResponse previousResponse)
 {
     if ((previousResponse == null) || !IsNtlmOrKerberos(previousResponse.AuthType))
     {
         request.KeepAlive       = false;
         request.ProtocolVersion = HttpVersion.Version10;
     }
 }
Beispiel #14
0
        /// <summary>
        ///  Initializes a new instance of the exception class with a specified
        ///  error code, error message and a reference to the inner exception that is the cause of
        ///  this exception.
        /// </summary>
        /// <param name="errorCode">The protocol error code returned by the service or generated by client. This is the code you can rely on for exception handling.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="serviceErrorCodes">The specific error codes that may be returned by the service.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified. It may especially contain the actual error message returned by the service.</param>
        public AdalServiceException(string errorCode, string message, string[] serviceErrorCodes, WebException innerException)
            : base(errorCode, message, innerException)
        {
            IHttpWebResponse response = NetworkPlugin.HttpWebRequestFactory.CreateResponse(innerException.Response);

            this.StatusCode        = (response != null) ? (int)response.StatusCode : 0;
            this.ServiceErrorCodes = serviceErrorCodes;
        }
        public IHttpResponse CreateHttpResponse(IHttpWebResponse webResponse, Stream body)
        {
            var deserializer = transmissionSettings.FindSerializer(webResponse.ContentType);

            return(new HttpResponse(
                       deserializer,
                       body,
                       webResponse.BuildState()));
        }
Beispiel #16
0
        public IHttpResponse CreateHttpResponse(IHttpWebResponse webResponse, Stream body)
        {
            var deserializer = transmissionSettings.FindSerializer(webResponse.ContentType);

            return new HttpResponse(
                deserializer,
                body,
                webResponse.BuildState());
        }
Beispiel #17
0
        /// <summary>
        /// Execute POST request - Async
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        protected async Task <IHttpWebResponse> ExecuteRequestAsync(string content)
        {
            using (IHttpWebRequest httpWebRequest = HttpWebRequest.Patch(this.RestUrl, content))
            {
                IHttpWebResponse httpWebResponse = await this.ExecuteRequestAsync(httpWebRequest);

                return(httpWebResponse);
            }
        }
 public static ExceptionDetail FromHttpResponse(IHttpWebResponse response)
 {
     return(new ExceptionDetail()
     {
         ResponseBody = response?.Body,
         StatusCode = response != null ? (int)response.StatusCode : -1,
         HttpResponseHeaders = response?.Headers
     });
 }
 /// <summary>
 /// Executes request.
 /// </summary>
 /// <returns></returns>
 public T Execute()
 {
     using (IHttpWebRequest httpWebRequest = HttpWebRequest.Get(this.RestUrl))
     {
         IHttpWebResponse httpWebResponse = this.ExecuteRequest(httpWebRequest);
         return(this.Deserialize <T>(
                    httpWebResponse,
                    this.DeserializationType));
     }
 }
        private void ProcessResponse(IHttpWebResponse httpWebResponse)
        {
            if (httpWebResponse.Cookies != null)
                Cookies = httpWebResponse.Cookies.Cast<Cookie>().ToList();

            using (var reader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                Content = reader.ReadToEnd();
            }
        }
Beispiel #21
0
 public Void Parse(IHttpWebResponse response)
 {
     using (response)
     {
         ResponseParseUtils.HandleStatusCode(response, HttpStatusCode.NoContent);
         var requestId = response.Headers.GetRequestIdFromHeader();
         Log.Debug($"Request: {requestId}");
         return(new Void());
     }
 }
Beispiel #22
0
        public static async Task <WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(wsTrustAddress.Uri.AbsoluteUri);

            request.ContentType = "application/soap+xml;";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            string        soapAction     = XmlNamespace.Issue.ToString();

            if (wsTrustAddress.Version == WsTrustVersion.WsTrust2005)
            {
                soapAction = XmlNamespace.Issue2005.ToString();
            }

            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                { "SOAPAction", soapAction }
            };

            WsTrustResponse wstResponse;

            try
            {
                HttpHelper.SetPostRequest(request, new RequestParameters(messageBuilder), callState, headers);
                IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState);

                wstResponse = WsTrustResponse.CreateFromResponse(response.GetResponseStream(), wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (AdalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new AdalServiceException(
                          AdalError.FederatedServiceReturnedError,
                          string.Format(AdalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                          null,
                          ex);
            }

            return(wstResponse);
        }
Beispiel #23
0
        public IHttpResponse CreateHttpResponse(IHttpWebResponse webResponse)
        {
            var deserializer = transmissionSettings.FindSerializer(webResponse.ContentType);
            var body = webResponse.ReadBody();

            return new HttpResponse(
                webResponse.ResponseUri,
                webResponse.StatusCode,
                body,
                deserializer);
        }
Beispiel #24
0
 public HttpWebHelperResult(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception exception, Exception innerException, bool isCancelled, bool completeSynchronsouly, Stream responseSaveStream, object state)
 {
     _httpWebRequest        = httpWebRequest;
     _httpWebResponse       = httpWebResponse;
     _exception             = exception;
     _innerException        = innerException;
     _isCancelled           = isCancelled;
     _completeSynchronsouly = completeSynchronsouly;
     _responseSaveStream    = responseSaveStream;
     _state = state;
 }
        /// <inheritdoc/>
        public async Task <WsTrustResponse> GetWsTrustResponseAsync(
            WsTrustEndpoint wsTrustEndpoint,
            string wsTrustRequest,
            RequestContext requestContext)
        {
            var headers = new Dictionary <string, string>
            {
                { "ContentType", "application/soap+xml" },
                { "SOAPAction", (wsTrustEndpoint.Version == WsTrustVersion.WsTrust2005) ? XmlNamespace.Issue2005.ToString() : XmlNamespace.Issue.ToString() }
            };

            var body = new StringContent(
                wsTrustRequest,
                Encoding.UTF8, headers["ContentType"]);

            IHttpWebResponse resp = await _httpManager.SendPostForceResponseAsync(wsTrustEndpoint.Uri, headers, body, requestContext).ConfigureAwait(false);

            if (resp.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string errorMessage = null;
                try
                {
                    errorMessage = WsTrustResponse.ReadErrorResponse(XDocument.Parse(resp.Body, LoadOptions.None), requestContext);
                }
                catch (System.Xml.XmlException)
                {
                    errorMessage = resp.Body;
                }

                throw MsalExceptionFactory.GetServiceException(
                          CoreErrorCodes.FederatedServiceReturnedError,
                          string.Format(
                              CultureInfo.CurrentCulture,
                              CoreErrorMessages.FederatedServiceReturnedErrorTemplate,
                              wsTrustEndpoint.Uri,
                              errorMessage),
                          new ExceptionDetail()
                {
                    StatusCode          = (int)resp.StatusCode,
                    ResponseBody        = resp.Body,
                    HttpResponseHeaders = resp.Headers
                });
            }

            try
            {
                return(WsTrustResponse.CreateFromResponse(resp.Body, wsTrustEndpoint.Version));
            }
            catch (System.Xml.XmlException ex)
            {
                throw MsalExceptionFactory.GetClientException(
                          CoreErrorCodes.ParsingWsTrustResponseFailed, CoreErrorCodes.ParsingWsTrustResponseFailed, ex);
            }
        }
 public HttpWebHelperResult(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception exception, Exception innerException, bool isCancelled, bool completeSynchronsouly, Stream responseSaveStream, object state)
 {
     _httpWebRequest = httpWebRequest;
     _httpWebResponse = httpWebResponse;
     _exception = exception;
     _innerException = innerException;
     _isCancelled = isCancelled;
     _completeSynchronsouly = completeSynchronsouly;
     _responseSaveStream = responseSaveStream;
     _state = state;
 }
Beispiel #27
0
        /// <summary>
        /// Return the character set encoding for an IHttpWebResponse, or null if no encoding is
        /// specified.
        /// </summary>
        ///
        /// <param name="response">
        /// The response.
        /// </param>
        ///
        /// <returns>
        /// The encoding, or null if no encoding was specified on the response, or the specified encoding
        /// was not recognized.
        /// </returns>

        public static Encoding GetEncoding(IHttpWebResponse response)
        {
            Encoding encoding = null;

            if (!String.IsNullOrEmpty(response.CharacterSet))
            {
                HtmlParser.HtmlEncoding.TryGetEncoding(response.CharacterSet, out encoding);
            }

            return(encoding);
        }
 private bool IsDeviceAuthChallenge(IHttpWebResponse response, bool respondToDeviceAuthChallenge)
 {
     return(DeviceAuthHelper.CanHandleDeviceAuthChallenge &&
            response != null &&
            respondToDeviceAuthChallenge &&
            response?.Headers != null &&
            response.StatusCode == HttpStatusCode.Unauthorized &&
            response.Headers.Contains(WwwAuthenticateHeader) &&
            response.Headers.GetValues(WwwAuthenticateHeader).FirstOrDefault()
            .StartsWith(PKeyAuthName, StringComparison.OrdinalIgnoreCase));
 }
        /// <summary>
        /// Execute request - ASYNC.
        /// </summary>
        /// <returns></returns>
        public async Task <T> ExecuteAsync()
        {
            using (IHttpWebRequest httpWebRequest = HttpWebRequest.Get(this.RestUrl))
            {
                IHttpWebResponse httpWebResponse = await this.ExecuteRequestAsync(httpWebRequest);

                return(this.Deserialize <T>(
                           httpWebResponse,
                           this.DeserializationType));
            }
        }
Beispiel #30
0
        private static IHttpWebResponse GetResponse(WebResponse response)
        {
            IHttpWebResponse response2 = response as IHttpWebResponse;

            if (response2 != null)
            {
                return(response2);
            }
            HttpWebResponse response3 = response as HttpWebResponse;

            return((response3 != null) ? new HttpWebResponseWrapper(response3) : null);
        }
Beispiel #31
0
        private void ProcessResponse(IHttpWebResponse httpWebResponse)
        {
            if (httpWebResponse.Cookies != null)
            {
                Cookies = httpWebResponse.Cookies.Cast <Cookie>().ToList();
            }

            using (var reader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                Content = reader.ReadToEnd();
            }
        }
Beispiel #32
0
 private static bool ShouldKeepAliveBeUsedInRequest(HttpWebRequest request, IHttpWebResponse response)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     if (response == null)
     {
         throw new ArgumentNullException("response");
     }
     return(!request.KeepAlive && IsNtlmOrKerberos(response.AuthType));
 }
Beispiel #33
0
        public virtual void GetResponse(IHttpWebRequest request, string filename, bool streamResponse)
        {
            try
            {
                _response = request.GetResponse();
            }
            catch (WebException webException)
            {
                if (webException.Response == null)
                {
                    throw;
                }
                _response = new HttpWebResponseWrapper((HttpWebResponse)webException.Response);
            }

            GetHeaders();

            if (streamResponse)
            {
                return;
            }

            using (var stream = _response.GetResponseStream())
            {
                if (stream == null)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(filename))
                {
                    using (var filestream = new FileStream(filename, FileMode.CreateNew))
                    {
                        int count;
                        var buffer = new byte[8192];

                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            filestream.Write(buffer, 0, count);
                        }
                    }
                }
                else
                {
                    var encoding = string.IsNullOrEmpty(CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(CharacterSet);
                    using (var reader = new StreamReader(stream, encoding))
                    {
                        RawText = reader.ReadToEnd();
                    }
                }
            }
        }
        internal static void HandleStatusCode(IHttpWebResponse response, params HttpStatusCode[] expectedStatusCodes)
        {
            var actualStatusCode = response.StatusCode;

            if (expectedStatusCodes.Contains(actualStatusCode))
            {
                return;
            }

            var errorResponse = GetErrorResponse(response);

            throw new ErrorResponseException(errorResponse);
        }
        public static TokenResponse CreateFromErrorResponse(IHttpWebResponse webResponse)
        {
            if (webResponse == null)
            {
                return new TokenResponse
                {
                    Error = AdalError.ServiceReturnedError,
                    ErrorDescription = AdalErrorMessage.ServiceReturnedError
                };
            }

            Stream responseStream = webResponse.ResponseStream;

            if (responseStream == null)
            {
                return new TokenResponse
                {
                    Error = AdalError.Unknown,
                    ErrorDescription = AdalErrorMessage.Unknown
                };
            }

            TokenResponse tokenResponse;

            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TokenResponse));
                tokenResponse = ((TokenResponse)serializer.ReadObject(responseStream));

                // Reset stream position to make it possible for application to read HttpRequestException body again
                responseStream.Position = 0;
            }
            catch (SerializationException)
            {
                responseStream.Position = 0;
                tokenResponse = new TokenResponse
                {
                    Error = (webResponse.StatusCode == HttpStatusCode.ServiceUnavailable) ?
                        AdalError.ServiceUnavailable :
                        AdalError.Unknown,
                    ErrorDescription = ReadStreamContent(responseStream)
                };
            }

            return tokenResponse;
        }
Beispiel #36
0
 private static void SetKeepAliveHeaders(HttpWebRequest request, IHttpWebResponse previousResponse)
 {
     // KeepAlive is required for NTLM and Kerberos authentication. If we've never been authenticated or are using a different auth, we 
     // should not require KeepAlive.
     // REVIEW: The WWW-Authenticate header is tricky to parse so a Equals might not be correct. 
     if (previousResponse == null ||
         (!String.Equals(previousResponse.AuthType, "NTLM", StringComparison.OrdinalIgnoreCase) &&
         !String.Equals(previousResponse.AuthType, "Kerberos", StringComparison.OrdinalIgnoreCase)))
     {
         // This is to work around the "The underlying connection was closed: An unexpected error occurred on a receive."
         // exception.
         request.KeepAlive = false;
         request.ProtocolVersion = HttpVersion.Version10;
     }
 }
Beispiel #37
0
 private static bool IsAuthenticationResponse(IHttpWebResponse response)
 {
     return response.StatusCode == HttpStatusCode.Unauthorized ||
            response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
 }
        private HttpWebHelperResult CopyResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseStream, Stream responseSaveStream)
        {
            try
            {
                CopyStream(responseStream, responseSaveStream, false, false);
                responseStream.Close();

                return new HttpWebHelperResult(httpWebRequest, httpWebResponse, null, innerException, false, true, responseSaveStream, null);
            }
            catch (Exception ex)
            {
                return new HttpWebHelperResult(httpWebRequest, httpWebResponse, ex, innerException, false, true, responseSaveStream, null);
            }
        }
 public HttpRequestWrapperException(IHttpWebResponse webResponse, Exception innerException) 
     : base(string.Empty, innerException)
 {
     this.WebResponse = webResponse;
 }
        private static void ReadResponseToFileStream(string localFilePath, IHttpWebResponse response)
        {
            IStream data = response.GetResponseStream();
            var byteBuffer = new byte[4096];
            using (IStream output = FileSystem.CreateStream(localFilePath, FileMode.Create))
            {
                int bytesRead;
                do
                {
                    bytesRead = data.Read(byteBuffer, 0, byteBuffer.Length);
                    if (bytesRead > 0)
                    {
                        output.Write(byteBuffer, 0, bytesRead);
                    }
                } while (bytesRead > 0);
            }

            data.Close();
            response.Close();
        }
Beispiel #41
0
 private Encoding TryGetEncoding(IHttpWebResponse response) {
     try {
         return Encoding.GetEncoding(response.CharacterSet);
     } catch {
         return Encoding.UTF8;
     }
 }
        private void CopyResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseStream, Stream responseSaveStream, AsyncCallback callback, object state)
        {
            if (AsyncResponseStream && responseSaveStream != null)
            {
                // pure read/write async
                CopyStreamAsync(responseStream, responseSaveStream, FlushResponseStream, FlushResponseSaveStream,
                                (source, destination, exception) =>
                                {
                                    source.Close();
                                    callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, false, responseSaveStream, state));
                                });
            }
            else
            {
                try
                {
                    if (responseSaveStream == null)
                        ReadStream(responseStream, FlushResponseStream);
                    else
                        CopyStream(responseStream, responseSaveStream, FlushResponseStream, FlushResponseSaveStream);

                    responseStream.Close();
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, null, innerException, false, false, responseSaveStream, state));
                }
                catch (Exception ex)
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, ex, null, false, false, responseSaveStream, state));
                }
            }
        }
Beispiel #43
0
        /// <summary>
        /// Return the character set encoding for an IHttpWebResponse, or null if no encoding is
        /// specified.
        /// </summary>
        ///
        /// <param name="response">
        /// The response.
        /// </param>
        ///
        /// <returns>
        /// The encoding, or null if no encoding was specified on the response, or the specified encoding
        /// was not recognized.
        /// </returns>

        public static Encoding GetEncoding(IHttpWebResponse response)
        {
            Encoding encoding = null;
            
            if (!String.IsNullOrEmpty(response.ContentType) 
                && response.ContentType.Contains("charset=")
                && !String.IsNullOrEmpty(response.CharacterSet)
                ) {
                HtmlParser.HtmlEncoding.TryGetEncoding(response.CharacterSet, out encoding);
            }
            
            return encoding;
        }
Beispiel #44
0
        static void SetKeepAliveHeaders(HttpWebRequest request, IHttpWebResponse previousResponse)
        {
            // KeepAlive is required for NTLM and Kerberos authentication. If we've never been authenticated or are
            // using a different auth, we should not require KeepAlive.
            // REVIEW: The WWW-Authenticate header is tricky to parse so a Equals might not be correct.
            if (previousResponse != null && IsNtlmOrKerberos (previousResponse.AuthType))
                return;

            // This is to work around the "The underlying connection was closed: An unexpected error occurred on a receive." exception.
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
        }
 public CouchDbResponse(IHttpWebResponse webResponse, Exception exception) : this(webResponse)
 {
     _exception = exception;
 }
 public CouchDbResponse(IHttpWebResponse webResponse)
 {
     _webResponse = webResponse;
 }
        public static TokenResponse CreateFromErrorResponse(IHttpWebResponse webResponse)
        {
            if (webResponse == null)
            {
                return new TokenResponse
                {
                    Error = MsalError.ServiceReturnedError,
                    ErrorDescription = MsalErrorMessage.ServiceReturnedError
                };
            }
            StringBuilder responseStreamString = new StringBuilder();
            TokenResponse tokenResponse = null;
            using (Stream responseStream = webResponse.ResponseStream)
            {
                if (responseStream == null)
                {
                    return new TokenResponse
                    {
                        Error = MsalError.Unknown,
                        ErrorDescription = MsalErrorMessage.Unknown
                    };
                }

                try
                {
                    responseStreamString.Append(ReadStreamContent(responseStream));
                    using (MemoryStream ms = new MemoryStream(responseStreamString.ToByteArray()))
                    {
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TokenResponse));
                        tokenResponse = ((TokenResponse)serializer.ReadObject(ms));
                    }
                }
                catch (SerializationException ex)
                {
                    PlatformPlugin.Logger.Warning(null, ex.Message);
                    tokenResponse = new TokenResponse
                    {
                        Error = (webResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
                            ? MsalError.ServiceUnavailable
                            : MsalError.Unknown,
                        ErrorDescription = responseStreamString.ToString()
                    };
                }
            }

            return tokenResponse;
        }
 public MirthConnectResponse(IHttpWebResponse httpWebResponse)
 {
     ProcessResponse(httpWebResponse);
 }
Beispiel #49
0
        /// <summary>
        /// Reads the full stream from the response and returns the content as stream,
        /// using the correct encoding.
        /// </summary>
        /// <param name="response">Web response from request to Solr</param>
        /// <returns></returns>
        private string ReadResponseToString(IHttpWebResponse response)
        {
            using (var responseStream = response.GetResponseStream())
				using (var reader = new StreamReader(responseStream, TryGetEncoding(response))) {
					return reader.ReadToEnd();
            }
        }
Beispiel #50
0
        /// <summary>
        /// Return the character set encoding for an IHttpWebResponse.
        /// </summary>
        ///
        /// <param name="response">
        /// The response.
        /// </param>
        ///
        /// <returns>
        /// The encoding, or null if no encoding was specified on the response, or the specified encoding
        /// was not recognized.
        /// </returns>

        public static Encoding GetEncoding(IHttpWebResponse response)
        {
            Encoding encoding = null;
            if (!String.IsNullOrEmpty(response.CharacterSet)) {
                EncodingInfo info;
                if (Encodings.TryGetValue(response.CharacterSet, out info))
                {
                    encoding = info.GetEncoding();
                }
            }
            
            return encoding;
        }
Beispiel #51
0
        static bool ShouldKeepAliveBeUsedInRequest(HttpWebRequest request, IHttpWebResponse response)
        {
            if (request == null)
                throw new ArgumentNullException ("request");

            if (response == null)
                throw new ArgumentNullException ("response");

            return !request.KeepAlive && IsNtlmOrKerberos (response.AuthType);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FluentHttpResponse"/> class.
 /// </summary>
 /// <param name="request">
 /// The fluent http web request.
 /// </param>
 /// <param name="httpWebResponse">
 /// The http web response.
 /// </param>
 public FluentHttpResponse(FluentHttpRequest request, IHttpWebResponse httpWebResponse)
     : this()
 {
     _request = request;
     _httpWebResponse = httpWebResponse;
 }
 public ResponseReceivedEventArgs(IHttpWebResponse response, Exception exception, object asyncState)
 {
     _response = response;
     _exception = exception;
     _asyncState = asyncState;
 }
Beispiel #54
0
        public WebResponse GetResponse()
        {
            _previousRequest = null;
            _previousResponse = null;
            _previousStatusCode = null;
            _usingSTSAuth = false;
            _continueIfFailed = true;
            _proxyCredentialsRetryCount = 0;
            _credentialsRetryCount = 0;
            int failureCount = 0;
            const int MaxFailureCount = 10;            

            while (true)
            {
                // Create the request
                var request = (HttpWebRequest)_createRequest();
                ConfigureRequest(request);

                try
                {
                    if (_disableBuffering)
                    {
                        request.AllowWriteStreamBuffering = false;

                        // When buffering is disabled, we need to add the Authorization header 
                        // for basic authentication by ourselves.
                        bool basicAuth = _previousResponse != null &&
                            _previousResponse.AuthType != null &&
                            _previousResponse.AuthType.IndexOf("Basic", StringComparison.OrdinalIgnoreCase) != -1;
                        var networkCredentials = request.Credentials.GetCredential(request.RequestUri, "Basic");
                        if (networkCredentials != null && basicAuth)
                        {
                            string authInfo = networkCredentials.UserName + ":" + networkCredentials.Password;
                            authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo));
                            request.Headers["Authorization"] = "Basic " + authInfo;
                            _basicAuthIsUsedInPreviousRequest = true;
                        }
                    }

                    // Prepare the request, we do something like write to the request stream
                    // which needs to happen last before the request goes out
                    _prepareRequest(request);                    

                    WebResponse response = request.GetResponse();                    

                    // Cache the proxy and credentials
                    _proxyCache.Add(request.Proxy);

                    ICredentials credentials = request.Credentials;
                    _credentialCache.Add(request.RequestUri, credentials);
                    _credentialCache.Add(response.ResponseUri, credentials);

                    return response;
                }
                catch (WebException ex)
                {
                    ++failureCount;
                    if (failureCount >= MaxFailureCount)
                    {
                        throw;
                    }

                    using (IHttpWebResponse response = GetResponse(ex.Response))
                    {
                        if (response == null &&
                            ex.Status != WebExceptionStatus.SecureChannelFailure)
                        {
                            // No response, something went wrong so just rethrow
                            throw;
                        }

                        // Special case https connections that might require authentication
                        if (ex.Status == WebExceptionStatus.SecureChannelFailure)
                        {
                            if (_continueIfFailed)
                            {
                                // Act like we got a 401 so that we prompt for credentials on the next request
                                _previousStatusCode = HttpStatusCode.Unauthorized;
                                continue;
                            }
                            throw;
                        }

                        // If we were trying to authenticate the proxy or the request and succeeded, cache the result.
                        if (_previousStatusCode == HttpStatusCode.ProxyAuthenticationRequired &&
                            response.StatusCode != HttpStatusCode.ProxyAuthenticationRequired)
                        {
                            _proxyCache.Add(request.Proxy);
                        }
                        else if (_previousStatusCode == HttpStatusCode.Unauthorized &&
                                 response.StatusCode != HttpStatusCode.Unauthorized)
                        {
                            _credentialCache.Add(request.RequestUri, request.Credentials);
                            _credentialCache.Add(response.ResponseUri, request.Credentials);
                        }

                        _usingSTSAuth = STSAuthHelper.TryRetrieveSTSToken(request.RequestUri, response);

                        if (!IsAuthenticationResponse(response) || !_continueIfFailed)
                        {
                            throw;
                        }

                        if (!EnvironmentUtility.IsNet45Installed &&
                            request.AllowWriteStreamBuffering == false &&
                            response.AuthType != null &&
                            IsNtlmOrKerberos(response.AuthType))
                        {
                            // integrated windows authentication does not work when buffering is 
                            // disabled on .net 4.0.
                            throw;
                        }

                        _previousRequest = request;
                        _previousResponse = response;
                        _previousStatusCode = _previousResponse.StatusCode;
                    }
                }
            }
        }
        /// <summary>
        /// Retrieve the information from the HTTP ResponseInfo stream
        /// </summary>
        /// <param name="httpResponse">Reponse object from random.org</param>
        /// <returns>JSON object containing response from random.org</returns>
        private static string GetResponse(IHttpWebResponse httpResponse)
        {
            string response = null;

            Stream responseStream = httpResponse.GetResponseStream();
            if (responseStream != null)
            {
                using (StreamReader reader = new StreamReader(responseStream))
                    response = reader.ReadToEnd();
            }

            return response;
        }
		public HttpWebResponse GetResponse(CancellationToken token)
		{
			_previousRequest = null;
			_previousResponse = null;
			_previousStatusCode = null;
			_usingSTSAuth = false;
			_continueIfFailed = true;
			_proxyCredentialsRetryCount = 0;
			_credentialsRetryCount = 0;
			int failureCount = 0;
			const int MaxFailureCount = 10;

			while (true)
			{
				// Create the request
				var request = (HttpWebRequest)_createRequest();
				MakeCancelable (request, token);
				ConfigureRequest(request);

				try
				{
					var auth = request.Headers["Authorization"];
					_basicAuthIsUsedInPreviousRequest = (auth != null)
						&& auth.StartsWith("Basic ", StringComparison.Ordinal);

					// Prepare the request, we do something like write to the request stream
					// which needs to happen last before the request goes out
					_prepareRequest(request);

					HttpWebResponse response = (HttpWebResponse)request.GetResponse();

					// Cache the proxy and credentials
					_proxyCache.Add(request.Proxy);

					ICredentials credentials = request.Credentials;
					_credentialCache.Add(request.RequestUri, credentials);
					_credentialCache.Add(response.ResponseUri, credentials);

					return response;
				}
				catch (WebException ex)
				{
					++failureCount;
					if (failureCount >= MaxFailureCount)
					{
						throw;
					}

					using (IHttpWebResponse response = GetResponse(ex.Response))
					{
						if (response == null &&
							ex.Status != WebExceptionStatus.SecureChannelFailure)
						{
							// No response, something went wrong so just rethrow
							throw;
						}

						// Special case https connections that might require authentication
						if (ex.Status == WebExceptionStatus.SecureChannelFailure)
						{
							if (_continueIfFailed)
							{
								// Act like we got a 401 so that we prompt for credentials on the next request
								_previousStatusCode = HttpStatusCode.Unauthorized;
								continue;
							}
							throw;
						}

						// If we were trying to authenticate the proxy or the request and succeeded, cache the result.
						if (_previousStatusCode == HttpStatusCode.ProxyAuthenticationRequired &&
							response.StatusCode != HttpStatusCode.ProxyAuthenticationRequired)
						{
							_proxyCache.Add(request.Proxy);
						}
						else if (_previousStatusCode == HttpStatusCode.Unauthorized &&
							response.StatusCode != HttpStatusCode.Unauthorized)
						{
							_credentialCache.Add(request.RequestUri, request.Credentials);
							_credentialCache.Add(response.ResponseUri, request.Credentials);
						}

						_usingSTSAuth = STSAuthHelper.TryRetrieveSTSToken(request.RequestUri, response);

						if (!IsAuthenticationResponse(response) || !_continueIfFailed)
						{
							throw;
						}

						_previousRequest = request;
						_previousResponse = response;
						_previousStatusCode = _previousResponse.StatusCode;
					}
				}
			}
		}
        private void ReadResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseSaveStream, AsyncCallback callback, object state)
        {
            Stream responseStream = null;
            Exception exception = null;

            try
            {
                responseStream = httpWebResponse.GetResponseStream();
            }
            catch (WebException ex)
            {
                exception = new WebExceptionWrapper(ex);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (exception == null)
                {
                    CopyResponseStream(httpWebRequest, httpWebResponse, innerException, responseStream, responseSaveStream, callback, state);
                }
                else
                {
                    if (callback != null)
                        callback(new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, null, false, false, responseSaveStream, state));
                }
            }
        }
Beispiel #58
0
        /// <summary>
        /// Return the character set encoding for an IHttpWebResponse
        /// </summary>
        ///
        /// <param name="response">
        /// The response.
        /// </param>
        ///
        /// <returns>
        /// The encoding.
        /// </returns>

        public static Encoding GetEncoding(IHttpWebResponse response)
        {
            return String.IsNullOrEmpty(response.CharacterSet) ?
               Encoding.GetEncoding("ISO-8859-1") :
               Encoding.GetEncoding(response.CharacterSet);

        }
        private HttpWebHelperResult ReadResponseStream(IHttpWebRequest httpWebRequest, IHttpWebResponse httpWebResponse, Exception innerException, Stream responseSaveStream)
        {
            Stream responseStream = null;
            Exception exception = null;

            try
            {
                responseStream = httpWebResponse.GetResponseStream();
            }
            catch (WebException ex)
            {
                exception = new WebExceptionWrapper(ex);
            }

            return exception == null ? CopyResponseStream(httpWebRequest, httpWebResponse, innerException, responseStream, responseSaveStream) : new HttpWebHelperResult(httpWebRequest, httpWebResponse, exception, innerException, false, true, responseSaveStream, null);
        }
        private static AuthenticationParameters CreateFromUnauthorizedResponseCommon(IHttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            AuthenticationParameters authParams;
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                if (response.Headers.Keys.Contains(AuthenticateHeader))
                {
                    authParams = CreateFromResponseAuthenticateHeader(response.Headers[AuthenticateHeader]);
                }
                else
                {
                    var ex = new ArgumentException(MsalErrorMessage.MissingAuthenticateHeader, "response");
                    PlatformPlugin.Logger.Error(null, ex);
                    throw ex;
                }
            }
            else
            {
                var ex = new ArgumentException(MsalErrorMessage.UnauthorizedHttpStatusCodeExpected, "response");
                PlatformPlugin.Logger.Error(null, ex);
                throw ex;
            }

            return authParams;
        }