Beispiel #1
1
        private static void RunClient()
        {
            // TEST CERTIFICATE ONLY, PLEASE REMOVE WHEN YOU REPLACE THE CERT WITH A REAL CERT
            // Perform the Server Certificate validation
            ServicePointManager.ServerCertificateValidationCallback += Program.RemoteCertificateValidationCallback;

            // set up the client without client certificate
            HttpClient client = new HttpClient();
            client.BaseAddress = _baseAddress;
            
            // set up the client with client certificate
            WebRequestHandler handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual; // this would pick from the Current user store
            handler.ClientCertificates.Add(GetClientCertificate());

            HttpClient clientWithClientCert = new HttpClient(handler);
            clientWithClientCert.BaseAddress = _baseAddress;
            HttpResponseMessage response;

            //// How to post a sample item with success
            SampleItem sampleItem = new SampleItem { Id = 1, StringValue = "hello from a new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting the first item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to post another sample item with success
            sampleItem = new SampleItem { Id = 2, StringValue = "hello from a second new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting a second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the two newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get an sample item with id = 2
            response = client.GetAsync("api/sample/2").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting the second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // Posting without client certificate will fail 
            sampleItem = new SampleItem { Id = 3, StringValue = "hello from a new sample item" };
            response = client.PostAsJsonAsync("api/sample/", sampleItem).Result;
            Console.WriteLine("Posting the third item without client certificate fails:\n" + response.StatusCode + "\n");
            response.Dispose();
        }
Beispiel #2
0
 public void Persist(TrackerData trackerData)
 {
     // setup the client
     // -   with a custome handler to approve all server certificates
     var handler = new WebRequestHandler
     {
         ServerCertificateValidationCallback =
             (sender, certificate, chain, errors) => true
     };
     try
     {
         using (var client = new HttpClient(handler))
         {
             // post it
             HttpResponseMessage httpResponseMessage = client.PostAsJsonAsync(_serviceUrl, trackerData).Result;
             if (!httpResponseMessage.IsSuccessStatusCode)
             {
                 Configurator.Configuration.Logger.Warn(string.Format("Data not persisted with status {0}",
                     httpResponseMessage.StatusCode));
             }
         }
     }
     catch (Exception ex)
     {
         Configurator.Configuration.Logger.Error(ex.Message, ex);
     }
 }
Beispiel #3
0
        static async Task execute(
                                    string authority,
                                    string resourceUri,
                                    string thisAppClientID,
                                    string thisAppKey,
                                    string epAddress
                                )
        {
            using (var handler = new WebRequestHandler())
            {
                handler.ServerCertificateValidationCallback += (sender, x509cert, chain, policyerrs) => { return true; };


                using (var client = new HttpClient(handler))
                {

                    var authToken = await getAuthToken(authority, 
                                                       resourceUri, 
                                                       thisAppClientID, 
                                                       thisAppKey);


                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authToken);
               //     client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "BS HERE");
                    
                    var response = await client.GetAsync(new Uri(epAddress));

                    Console.WriteLine("ep: {0} - Response: {1}", epAddress, response.StatusCode);
                }

            }
        }
 private WebRequestHandler getWebRequestHandlerWithCert(string certFilename)
 {
     var cert = new X509Certificate2(certFilename, "");
     var clientHandler = new WebRequestHandler();
     clientHandler.ClientCertificates.Add(cert);
     return clientHandler;
 }
Beispiel #5
0
        public async Task ProcessAttachment(long incidentId, string fileName)
        {
            String fileAsBase64 = Convert.ToBase64String(File.ReadAllBytes(fileName));
            AttachmentWrapper payload = new AttachmentWrapper();
            payload.Attachment = IncidentAttachment.CreateIncidentAttachment(Path.GetFileName(fileName), fileAsBase64);

            string createAttachementUri = "https://icm.ad.msft.net/api/cert/incidents(" + incidentId
                                          + ")/CreateAttachment";
            Logger.DebugFormat("CreateAttachementUri {0}", createAttachementUri);

            try
            {
                using (WebRequestHandler handler = new WebRequestHandler())
                {
                    handler.ClientCertificates.Add(certificate);

                    using (HttpClient client = new HttpClient(handler))
                    {
                        client.BaseAddress = new Uri(createAttachementUri);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var response = await client.PostAsJsonAsync(createAttachementUri, payload);
                        Logger.InfoFormat(response.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(ex.ToString());
            }
        }
        //static Uri _baseAddress = new Uri(Constants.SelfHostBaseAddress);

        static void Main(string[] args)
        {
            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling Service\n".ConsoleYellow();

                    var handler = new WebRequestHandler();
                    handler.ClientCertificates.Add(
                        X509.
                        CurrentUser.
                        My.
                        SubjectDistinguishedName.
                        Find("CN=Client").First());

                    var client = new HttpClient(handler) { BaseAddress = _baseAddress };
                    
                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var identity = response.Content.ReadAsAsync<Identity>().Result;
                    identity.ShowConsole();
                });

                Console.ReadLine();
            }
        }
        public SystemNetHttpClientAdapter(AdapterOptions options)
        {
            _autoRedirect = options.AutoRedirect;
            var handler = new WebRequestHandler
            {
                AllowAutoRedirect = !(AutoRedirect.AutoRedirectAndForwardAuthorizationHeader.Equals(options.AutoRedirect) ||
                                      AutoRedirect.DoNotAutoRedirect.Equals(options.AutoRedirect)),
                UseCookies = false,
            };

            if (options.CachePolicy.Cache)
            {
                handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
            }

            if (options.AcceptEncoding.AcceptGzipAndDeflate)
            {
                handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            }

            _client = new HttpClient(handler);

            if (options.Timeout != null)
            {
                _client.Timeout = options.Timeout.TimeSpan;
            }
        }
        static void Main(string[] args)
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificates.Add(
                X509.CurrentUser
                    .My
                    .SubjectDistinguishedName
                    .Find("CN=client")
                    .First());

            //var handler = new HttpClientHandler
            //{
            //    ClientCertificateOptions = ClientCertificateOption.Automatic
            //};

            var client = new HttpClient(handler)
            {
                BaseAddress = new Uri("https://web.local:444/api/")
            };

            client.SetBasicAuthentication("bob", "bob");

            var result = client.GetStringAsync("identity").Result;
            Console.WriteLine(JArray.Parse(result));
        }
        protected override async Task RunAsync(HttpApiContext context)
        {
            using (WebRequestHandler handler = new WebRequestHandler())
            {
                handler.UseCookies = false;
                handler.AllowAutoRedirect = false;
                handler.ServerCertificateValidationCallback = delegate { return true; };
                //handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
                using (HttpClient client = new HttpClient(handler))
                {
                    HttpRequestMessage request = Create(context.Request);

                    var response = await client.SendAsync(request);


                    var data = await response.Content.ReadAsByteArrayAsync();

                    context.Response = SetResponse(response, data);
                    var ct = response.Content.Headers.ContentType;
                    if (ct != null)
                    {
                        context.Response.ContentType = ct.ToString();
                    }

                    //context.Response.ContentType = response.Content.Headers.ContentType.ToString();
                }
            }
        }
        public BuildStatusCollection Check()
        {
            var status = new BuildStatusCollection();
            string response = "NO RESPONSE";

            try
            {
                var webRequestHandler = new WebRequestHandler();
                if (!string.IsNullOrWhiteSpace(Settings.Default.TeamCityUser) && !string.IsNullOrWhiteSpace(Settings.Default.TeamCityPassword))
                {
                    webRequestHandler.Credentials = new NetworkCredential(Settings.Default.TeamCityUser, Settings.Default.TeamCityPassword);
                }
                using (var client = new HttpClient(webRequestHandler))
                {
                    client.BaseAddress = new Uri(Settings.Default.TeamCityUrl);
                    logger.Debug("Getting status from TeamCity at URL [{0}] with user [{1}] and password [{2}]", new Uri(client.BaseAddress, REQUEST_PATH), Settings.Default.TeamCityUser ?? "Anonymous",
                                 Settings.Default.TeamCityPassword ?? "N/A");
                    response = client.GetStringAsync(REQUEST_PATH).Result;
                    logger.Debug("Response from server is {0}", response);
                    return new BuildStatusCollection(response);
                }
            }
            catch (Exception err)
            {
                logger.ErrorException(
                    string.Format(
                        "Unexpected exception occured when checking status at TeamCity.  URL [{0}], User [{1}], Password [{2}], RawResponse [{3}]",
                        Settings.Default.TeamCityUrl ?? " NULL", Settings.Default.TeamCityUser ?? "Anonymous",
                        Settings.Default.TeamCityPassword ?? "N/A", response), err);
            }

            return status;
        }
        public async Task HttpClientJsonRequestTest()
        {
            var handler = new WebRequestHandler();
            //handler.Proxy = new WebProxy("http://localhost:8888/");
            //handler.Credentials = new NetworkCredential(uid, pwd);            

            var client = new HttpClient(handler);

            var postSnippet = new CodeSnippet()
            {
                UserId = "Bogus",
                Code = "string.Format('Hello World, I will own you!');",
                Comment = "World domination imminent"
            };

            // this isn't actually an API so the POST is ignored
            // but it always returns a JSON response 
            string url = "http://codepaste.net/recent?format=json";

            var response = await client.PostAsync(url, postSnippet,
                                                  new JsonMediaTypeFormatter(), null);

            Assert.IsTrue(response.IsSuccessStatusCode);

            var snippets = await response.Content.ReadAsAsync<List<CodeSnippet>>();
            Assert.IsTrue(snippets.Count > 0);

            foreach (var snippet in snippets)
            {
                if (string.IsNullOrEmpty(snippet.Code))
                    continue;
                Console.WriteLine(snippet.Code.Substring(0, Math.Min(snippet.Code.Length, 200)));
                Console.WriteLine("--");
            }
        }
        public HttpClient CreateWebClient()
        {
            if(handler == null)
            {
                if (ClientCertificate == null)
                    throw new NullReferenceException("ClientCertificate is null.");

                if (ServerCertificateValidator == null)
                    throw new NullReferenceException("ServerCertificateValidator is null.");

                if (BaseUrl == null)
                    throw new NullReferenceException("BaseUrl is null.");

                handler = new WebRequestHandler();
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ClientCertificates.Add(ClientCertificate);
                handler.ServerCertificateValidationCallback = ServerCertificateValidator;
            }

            if (client == null)
            {
                client = new HttpClient(handler);
                client.DefaultRequestHeaders.Add("x-devupdater-client-version", version.ToString()); // send version (next version will be able to reject older versions)
            }

            return client;
        }
 public void Dispose()
 {
     if (handler != null)
     {
         handler.Dispose();
         handler = null;
     }
 }
 internal HttpClientAbstraction(HttpClient client, IAbstractionContext context, WebRequestHandler handler, bool ignoreSslErrors)
     : this(client, handler, ignoreSslErrors)
 {
     if (context.Logger.IsNotNull())
     {
         this.instanceLogger = context.Logger;
     }
     this.cancellationToken = context.CancellationToken;
 }
 /// <summary>
 /// Allan Alderman 1-10-2014
 /// Assembles a VM Managment client, attaching the correct management certificate.
 /// </summary>
 /// <returns>An HTTP client that is ready and authorized to issue commands to Azure's REST API.</returns>
 public static HttpClient CreateVMManagementClient()
 {
     if (_http != null) return _http;
     var handler = new WebRequestHandler();
     handler.ClientCertificates.Add(ConstructX509Certificate());
     _http = new HttpClient(handler) {BaseAddress = new Uri(AzureVmRestApiUri)};
     _http.DefaultRequestHeaders.Add("x-ms-version", "2013-08-01");
     return _http;
 }
 private HttpClient initHttpClientInstance(WebRequestHandler clientHandler, string appKey, string baseUrl = DEFAULT_COM_BASEURL)
 {
     var client = new HttpClient(clientHandler);
     client.BaseAddress = new Uri(baseUrl);
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Add("X-Application", appKey);
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     return client;
 }
Beispiel #17
0
 // We use the same HttpClient for all calls to the same subscription; this allows DNS and proxy details to be
 // cached across requests. Note that HttpClient allows parallel operations.
 internal static HttpClient CreateHttpClient (Subscription subscription, string msVersion, Func<IEnumerable<TraceListener>> listenerFunc)
 {
     var handler = new WebRequestHandler();
     handler.ClientCertificates.Add(subscription.ManagementCertificate);
     var logger = new LoggingHandler(handler, listenerFunc);
     var client = new HttpClient(logger, true);
     client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
     return client;
 }
        public static IAuthenticationProvider CreateAuthenticationProvider(IAuthenticationInfo authenticationInfo, Uri baseAddress, TimeSpan? serviceTimeout = null, bool continueAsyncTasksOnCapturedContext = false, Action<HttpClient> postHttpClientInitializeAction = null)
        {
            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AppId)
            {
                return new AppIdAuthenticationProvider(authenticationInfo as AppIdAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AppRole)
            {
                return new AppRoleAuthenticationProvider(authenticationInfo as AppRoleAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AwsEc2)
            {
                return new AwsEc2AuthenticationProvider(authenticationInfo as AwsEc2AuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.GitHub)
            {
                return new GitHubAuthenticationProvider(authenticationInfo as GitHubAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.LDAP)
            {
                return new LDAPAuthenticationProvider(authenticationInfo as LDAPAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.Certificate)
            {
                var certificationInfo = authenticationInfo as CertificateAuthenticationInfo;

                var handler = new WebRequestHandler();
                handler.ClientCertificates.Add(certificationInfo.ClientCertificate);

                return new CertificateAuthenticationProvider(certificationInfo, new HttpDataAccessManager(baseAddress, handler, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.Token)
            {
                return new TokenAuthenticationProvider(authenticationInfo as TokenAuthenticationInfo);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.UsernamePassword)
            {
                return new UsernamePasswordAuthenticationProvider(authenticationInfo as UsernamePasswordAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            var customAuthenticationInfo = authenticationInfo as CustomAuthenticationInfo;

            if (customAuthenticationInfo != null)
            {
                return new CustomAuthenticationProvider(customAuthenticationInfo, continueAsyncTasksOnCapturedContext);
            }

            throw new NotSupportedException("The requested authentication backend type is not supported: " + authenticationInfo.AuthenticationBackendType);
        }
        public static HttpClient CreateHttpClient()
        {
            var serviceAccount = System.Configuration.ConfigurationManager.AppSettings["RsApiServiceUser"];
            var serviceAccountPass = System.Configuration.ConfigurationManager.AppSettings["RsApiServiceUserPass"];
            /*
            var handler = new HttpClientHandler()
                              {
                                  // UseDefaultCredentials = true
                                  Credentials =
                                      new NetworkCredential(
                                      serviceAccount,
                                      serviceAccountPass, "NRECA")
                              };

            var handler = new HttpClientHandler()
            {
                UseDefaultCredentials = true

            };
            */
            WebRequestHandler handler;
            if (string.IsNullOrEmpty(serviceAccount))
            {
                handler = new WebRequestHandler
                {
                    UseDefaultCredentials = true

                };
            }
            else
            {
                handler = new WebRequestHandler
                {
                    // UseDefaultCredentials = true
                    Credentials =
                     new NetworkCredential(
                     serviceAccount,
                     serviceAccountPass, "NRECA")
                };
            }

            handler.PreAuthenticate = true;
            handler.UnsafeAuthenticatedConnectionSharing = true;

               handler.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            var rsHttpClient = new HttpClient(handler);
            var url = System.Configuration.ConfigurationManager.AppSettings["RsApiUrl"];
            rsHttpClient.BaseAddress = new Uri(url);
            rsHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json"));

            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, certificate, chain, sslPolicyErrors) => true;

            return rsHttpClient;
        }
        public CertificateCredentials(X509Certificate2 clientCertificate)
        {
            _handler = new WebRequestHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                UseDefaultCredentials = false
            };

            _handler.ClientCertificates.Add(clientCertificate);
        }
Beispiel #21
0
        private static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                Console.WriteLine("Enter PIN: ");
                string pin = Console.ReadLine();

                WebRequestHandler handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                using (HttpClient client = new HttpClient(handler, true))
                {
                    client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort));

                    X509Store store = null;

                    try
                    {
                        var response = await client.GetAsync("certs/" + pin);
                        response.EnsureSuccessStatusCode();

                        byte[] rawCert = await response.Content.ReadAsByteArrayAsync();

                        X509Certificate2Collection certs = new X509Certificate2Collection();
                        certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet);

                        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                        store.Open(OpenFlags.ReadWrite);

                        X509Certificate2Collection oldCerts = new X509Certificate2Collection();

                        foreach (var cert in certs)
                        {
                            oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false));
                        }
                        store.RemoveRange(certs);
                        store.AddRange(certs);
                        store.Close();

                        Console.WriteLine("Success");
                    }
                    catch (HttpRequestException e)
                    {
                        Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated.");
                    }
                    finally
                    {
                        if (store != null)
                        {
                            store.Close();
                        }
                    }
                }
            }).Wait();
        }
Beispiel #22
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="options">options to initialize</param>
        public EtcdClient(EtcdClientOpitions options)
        {
            if (options == null)
                throw new ArgumentNullException("options");
            if (options.Urls == null || options.Urls.Length == 0)
                throw new ArgumentException("`EtcdClientOpitions.Urls` does not contain valid url");

            WebRequestHandler handler = new WebRequestHandler()
            {
                UseProxy = options.UseProxy,
                AllowAutoRedirect = false,
                AllowPipelining = true,
                CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore),
            };
            if (options.X509Certificate != null)
                handler.ClientCertificates.Add(options.X509Certificate);

            AuthenticationHeaderValue authenticationHeaderValue = null;
            if( !string.IsNullOrWhiteSpace(options.Username) &&
                !string.IsNullOrWhiteSpace(options.Password) )
            {
                string auth = string.Format("{0}:{1}", options.Username, options.Password);
                authenticationHeaderValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(auth)));
            }

            _jsonDeserializer = options.JsonDeserializer == null ? new DefaultJsonDeserializer() : options.JsonDeserializer;

            if (options.IgnoreCertificateError)
                handler.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; };

            HttpClientEx [] httpClients = options.Urls.Select(u =>
                {
                    if (string.IsNullOrWhiteSpace(u))
                        throw new ArgumentNullException("`urls` array contains empty url");

                    HttpClientEx httpClient = new HttpClientEx(handler);
                    httpClient.BaseAddress = new Uri(u);
                    httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
                    return httpClient;
                }).ToArray();

            // make the clients as a ring, so that we can try the next one when one fails
            if( httpClients.Length > 1 )
            {
                for( int i = httpClients.Length - 2; i >= 0; i--)
                {
                    httpClients[i].Next = httpClients[i + 1];
                }
            }
            httpClients[httpClients.Length - 1].Next = httpClients[0];

            // pick a client randomly
            _currentClient = httpClients[DateTime.UtcNow.Ticks % httpClients.Length];
        }
    protected override HttpMessageHandler CreateHandler (CreateHttpClientArgs args)
    {
      var webRequestHandler = new WebRequestHandler()
                              {
                                  Proxy = _proxyOrNull,
                                  UseProxy = (_proxyOrNull != null),
                                  UseCookies = false
                              };

      return webRequestHandler;
    }
 internal HttpClientAbstraction(HttpClient client, WebRequestHandler handler, bool ignoreSslErrors)
 {
     this.client = client;
     this.ignoreSslErrors = ignoreSslErrors;
     this.Timeout = DefaultTimeout;
     this.Method = HttpMethod.Get;
     handler.ServerCertificateValidationCallback += this.ServerCertificateValidationCallback;
     this.RequestHeaders = new Dictionary<string, string>();
     this.ContentType = HttpConstants.ApplicationXml;
     this.instanceLogger = new Logger();
 }
 public async Task Azure_blob_has_MSFT_cert_in_path()
 {
     var h = new WebRequestHandler();
     h.SetValidator(info =>
         !info.HasErrors &&
         new AtLeastOneThumbprintInCertChain(msftThumbs).Eval(info));
     using (var client = new HttpClient(h))
     {
         await client.GetAsync("https://webapibook.blob.core.windows.net/");
     }
 }
Beispiel #26
0
        public HttpRequester()
        {
            var requestHandler = new WebRequestHandler
                                 {
                                     AllowPipelining = true,
                                     CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore),
                                     AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                                 };

            this.client = new HttpClient(requestHandler, disposeHandler: true);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> values;
            try
            {
                if (request.Headers.TryGetValues("X-ClusterMonitor-Proxy", out values))
                {
                    if (values.Any())
                    {
                        UriBuilder ub = new UriBuilder(request.RequestUri);
                        ub.Path = ub.Path.Replace("/cluster", String.Empty);
                        ub.Port = Int32.Parse(values.First());

                        WebRequestHandler handler = new WebRequestHandler();

                        if (!String.IsNullOrEmpty(this.secureClusterCertThumbprint))
                        {
                            X509Certificate2 cert = GetCertificate(this.secureClusterCertThumbprint);

                            if (cert != null)
                            {
                                if (!(handler.ClientCertificates.Contains(cert)))
                                {
                                    handler.ClientCertificates.Add(cert);
                                    handler.ServerCertificateValidationCallback += (sender, cert2, chain, sslPolicyErrors) => true;

                                    ub.Scheme = "https";
                                }
                            }
                        }

                        HttpClient client = new HttpClient(handler);

                        return client.GetAsync(ub.Uri, HttpCompletionOption.ResponseContentRead, cancellationToken);
                    }
                }
            }
            catch (Exception ex)
            {
                object resultObject = null;
                //HttpStatusCode statusCode = m_exceptionHandler != null
                //    ? m_exceptionHandler.HandleException(ex, out resultObject)
                //    : HttpStatusCode.InternalServerError;

                HttpStatusCode statusCode = HttpStatusCode.InternalServerError;

                HttpResponseMessage responseMessage = request.CreateResponse(statusCode, resultObject ?? ex);

                return Task<HttpResponseMessage>.Factory.StartNew(() => responseMessage);
            }

            return base.SendAsync(request, cancellationToken);
        }
        public AccessTokenResponse RequestAccessTokenCertificate(X509Certificate2 certificate, string scope)
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificates.Add(certificate);

            var client = new HttpClient(handler) { BaseAddress = _client.BaseAddress };
            var response = client.PostAsync("", CreateFormCertificate(scope)).Result;
            response.EnsureSuccessStatusCode();

            var json = JsonValue.Parse(response.Content.ReadAsStringAsync().Result).AsDynamic();
            return CreateResponseFromJson(json);
        }
        public override HttpClient BuildHttpClient()
        {
            WebRequestHandler certHandler = new WebRequestHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                UseDefaultCredentials = false
            };

            certHandler.ClientCertificates.Add(this.ClientCertificate);

            return new HttpClient(certHandler);
        }
 private HttpClient CreateClient(double timeout)
 {
     var requestHandler = new WebRequestHandler
     {
         AllowPipelining = true,
         AllowAutoRedirect = true,
         CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate)
     };
     var client = HttpClientFactory.Create(requestHandler);
     client.Timeout = TimeSpan.FromMilliseconds(timeout);
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
     return client;
 }
Beispiel #31
0
        async Task RequestAsync(int id)
        {
            var handler = new System.Net.Http.WebRequestHandler();

            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SSLCertThmbprint"]))
            {
                //Perfome SSL Pinning. It is required to get SHA1 thumbprint of the SSL Server Certificate
                //and put it in the appSettings
                //Maybe the Key Identifier should be used. But the first version we should simply use SHA1 thumbprint.
                handler.ServerCertificateValidationCallback = (sender, cert, chain, error) =>
                {
                    var fixedSID = System.Configuration.ConfigurationManager.AppSettings["SSLCertThmbprint"];
                    var ch       = X509Chain.Create();
                    ch.ChainPolicy = new X509ChainPolicy
                    {
                        RevocationFlag = X509RevocationFlag.EndCertificateOnly,
                        RevocationMode = X509RevocationMode.NoCheck
                    };

                    //It is required to build the certificate chain upto the TRUSTED ROOT located in
                    //TRUST ROOT Certficate Store
                    if (ch.Build(cert as X509Certificate2))
                    {
                        foreach (var s in ch.ChainStatus)
                        {
                            if (s.Status != X509ChainStatusFlags.NoError)
                            {
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        return(false);
                    }

                    //And finally compare the thumbprints.
                    var    cert2    = cert as X509Certificate2;
                    string sidValue = cert2.Thumbprint.ToLower();

                    if (string.IsNullOrEmpty(sidValue))
                    {
                        sidValue = BitConverter.ToString(
                            (new SHA1Managed()).ComputeHash(cert2.GetPublicKey())).Replace("-", string.Empty).ToLower();
                    }

                    if (string.IsNullOrEmpty(sidValue))
                    {
                        return(false);
                    }

                    if (sidValue == fixedSID)
                    {
                        return(true);
                    }
                    return(false);
                };
            }

            //Loading the client certificate to setup SSL Client Authentication.
            var clientCertFile    = System.Configuration.ConfigurationManager.AppSettings["SSLClientCert"];
            var clientCertFilePwd = System.Configuration.ConfigurationManager.AppSettings["SSLClientCertPwd"];
            var clientCert        = new X509Certificate2(clientCertFile, clientCertFilePwd);

            handler.ClientCertificates.Add(clientCert);

            var client      = new HttpClient(handler);
            var url         = _apiUrl + id;
            var outgoing    = new Uri(url);
            var httpRequest = new HttpRequestMessage(HttpMethod.Get, outgoing);
            var response    = await client.SendAsync(httpRequest).ConfigureAwait(false);

            _statusCode = response.StatusCode;
            _rawMessage = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }