예제 #1
0
        public static HttpClient CreateHttpClient(IProxyAndRecordSettings settings)
        {
#if NETSTANDARD
            var handler = new HttpClientHandler
            {
                CheckCertificateRevocationList = false,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls,
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
#elif NET46
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#else
            var handler = new WebRequestHandler
            {
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#endif

            if (!string.IsNullOrEmpty(settings.ClientX509Certificate2ThumbprintOrSubjectName))
            {
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;

                var x509Certificate2 = ClientCertificateHelper.GetCertificate(settings.ClientX509Certificate2ThumbprintOrSubjectName);
                handler.ClientCertificates.Add(x509Certificate2);
            }

            handler.AllowAutoRedirect = settings.AllowAutoRedirect == true;

            // If UseCookies enabled, httpClient ignores Cookie header
            handler.UseCookies = false;

            if (settings.WebProxySettings != null)
            {
                handler.UseProxy = true;

                handler.Proxy = new WebProxy(settings.WebProxySettings.Address);
                if (settings.WebProxySettings.UserName != null && settings.WebProxySettings.Password != null)
                {
                    handler.Proxy.Credentials = new NetworkCredential(settings.WebProxySettings.UserName, settings.WebProxySettings.Password);
                }
            }

            var client = new HttpClient(handler);
#if NET452 || NET46
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
#endif
            return(client);
        }
예제 #2
0
        public async void ClientCertificateHelper_ValidateCertificate_NonExistingThumbprint_ReturnsFail()
        {
            // Arrange
            var thumbprint = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

            // Act
            var result = await ClientCertificateHelper.ValidateCertificate(thumbprint, StoreName.My, StoreLocation.LocalMachine,
                                                                           false, true, HealthStatus.Unhealthy);

            // Assert
            Assert.Equal(HealthStatus.Unhealthy, result.Status);
            Assert.Contains(" was not found in", result.Description);
        }
예제 #3
0
        public static HttpClient CreateHttpClient(string clientX509Certificate2ThumbprintOrSubjectName = null)
        {
#if NETSTANDARD
            var handler = new HttpClientHandler
            {
                CheckCertificateRevocationList = false,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls,
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
#elif NET46
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#else
            var handler = new WebRequestHandler
            {
                ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
#endif

            if (!string.IsNullOrEmpty(clientX509Certificate2ThumbprintOrSubjectName))
            {
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;

                var x509Certificate2 = ClientCertificateHelper.GetCertificate(clientX509Certificate2ThumbprintOrSubjectName);
                handler.ClientCertificates.Add(x509Certificate2);
            }

            // For proxy we shouldn't follow auto redirects
            handler.AllowAutoRedirect = false;

            // If UseCookies enabled, httpClient ignores Cookie header
            handler.UseCookies = false;

            var client = new HttpClient(handler);
#if NET452 || NET46
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
#endif
            return(client);
        }
예제 #4
0
        public async void ClientCertificateHelper_ValidateCertificate_CertificateWithoutPrivateKey_WhenRequirePrivateKey_ReturnsFail()
        {
            // Arrange
            // Fetch a thumbprint from a cert hopefully already in store... could we assume it exists one? Or must insert cert in test case?
            var thumbprint          = GetThumbprint(StoreName.My, StoreLocation.LocalMachine, false, true);
            var anExistingCertFound = thumbprint != null;

            Assert.True(anExistingCertFound,
                        "No existing suitable cert found in store for this test (add or rewrite test needed...)");

            // Act
            var result = await ClientCertificateHelper.ValidateCertificate(thumbprint, StoreName.My, StoreLocation.LocalMachine,
                                                                           true, true, HealthStatus.Unhealthy);

            // Assert
            Assert.Equal(HealthStatus.Unhealthy, result.Status);
            Assert.Contains("has no corresponding private key", result.Description);
        }
예제 #5
0
        public static OAUTHtoken GetOAUTHToken()
        {
            Result returnResult = new Result();

            Assembly      assembly  = Assembly.GetExecutingAssembly();
            GuidAttribute attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
            String        id        = attribute.Value;

            X509Certificate2 clientCert = ClientCertificateHelper.GetClientCertificate("RGDAT108VCC");

            OAUTHtoken OAUTHtokenReturned = new OAUTHtoken();

            using (HttpClient quangoPingClient = NetworkHelper.GetHttpClient("https://beta-sso.cognisec.com:9998", new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"), clientCert))   //Get an instance of HttpClient and populate with token and stuff
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "client_credentials")                                           //Ping expects a Form with client credentials request
                }
                                                        );
                string quangoPingUri = "/as/token.oauth2?client_id=cc_" + id;                                                                           //Ping OAUTH URI set, ready to pass to HttpClient
                try
                {
                    using (HttpResponseMessage quangoPingResponse = quangoPingClient.PostAsync(quangoPingUri, content).Result)      //Attempt to POST the form and extract Result
                    {
                        if (quangoPingResponse.StatusCode != HttpStatusCode.OK)                                                     //Connected to host, but got non-OK HTTP back
                        {
                            try
                            {
                                OAUTHerror OAUTHerrorReturned = JsonConvert.DeserializeObject <OAUTHerror>(quangoPingResponse.Content.ReadAsStringAsync().Result);   //Attempt to get OAUTHerror
                                returnResult.ExceptionInfo = OAUTHerrorReturned.error_description;
                                returnResult.ResultText    = "OAUTH token error";
                            }
                            catch (Exception ex)
                            {
                                returnResult.ExceptionInfo = ex.Message;                                                                                            //No OAUTHerror found
                                returnResult.ResultText    = "OAUTH response deserialisation failed - HTTP status code " + quangoPingResponse.StatusCode;           //so just send status code
                            }
                            returnResult.Outcome = "Fail";
                        }
                        else
                        {
                            OAUTHtokenReturned = JsonConvert.DeserializeObject <OAUTHtoken>(quangoPingResponse.Content.ReadAsStringAsync().Result);

                            returnResult.Outcome = "Success";
                        }
                    }
                }
                catch (Exception ex)                                                    //Failed to connect to host
                {
                    returnResult.ExceptionInfo = ex.InnerException.InnerException.Message;
                    returnResult.ResultText    = "Failed to contact token provider";
                    returnResult.Outcome       = "Fail";
                }

                if (returnResult.Outcome.Equals("Fail"))                                //Inform the user of the failure
                {
                    //  result.Text("Outcome " + returnResult.Outcome);
                    //  result.Text("ResultText " + returnResult.ResultText);
                    //  result.Text("ExceptionInfo " + returnResult.ExceptionInfo);
                    string fail = "Outcome " + returnResult.Outcome;
                    fail += "\nResultText " + returnResult.ResultText;
                    fail += "\nExceptionInfo " + returnResult.ExceptionInfo;

                    throw new Exception(fail);
                }
            }
            return(OAUTHtokenReturned);
        }