public static PoolingHttpClientConnectionManager getConnctionManager(){ Registry<ConnectionSocketFactory> socketFactoryRegistry = null; try { SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier()); socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory> create() .register("http", new PlainConnectionSocketFactory()) .register("https", trustSelfSignedSocketFactory) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { Data.logger.warn("", e); } PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry): new PoolingHttpClientConnectionManager(); // twitter specific options cm.setMaxTotal(2000); cm.setDefaultMaxPerRoute(200); return cm; }
public String notifyHunter(byte[] content) throws IOException { try { String request = new String(content); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection"); String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}"; StringEntity entity = new StringEntity(json); entity.setContentType("applicaiton/json"); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); String responseString = new BasicResponseHandler().handleResponse(response); return responseString; } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex); } return "Error Notifying Probe Server!"; }
@Test public void testHome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue( "Result is not Matched with Server Response",entity.getBody().contains("welcome to the application")); }
public void init() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); /* 配置同时支持 HTTP 和 HTPPS */ Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build(); /* 初始化连接管理器 */ poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); poolConnManager.setMaxTotal(maxTotal); poolConnManager.setDefaultMaxPerRoute(defaultMaxPerRoute); requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout) .setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build(); httpClient = getConnection(); log.info("HttpConnectionManager初始化完成..."); } catch (Exception e) { log.error("error", e); } }
private static HttpClient createAllTrustingClient() throws RestClientException { HttpClient httpclient = null; try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial((TrustStrategy) (X509Certificate[] chain, String authType) -> true); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); httpclient = HttpClients .custom() .setSSLSocketFactory(sslsf) .setMaxConnTotal(1000) .setMaxConnPerRoute(1000) .build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new RestClientException("Cannot create all SSL certificates trusting client", e); } return httpclient; }
public HttpFederationClient(HomeserverState global, FederationDomainResolver resolver) { this.global = global; this.resolver = resolver; try { SocketConfig sockConf = SocketConfig.custom().setSoTimeout(30000).build(); // FIXME properly handle SSL context by validating certificate hostname SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build(); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); this.client = HttpClientBuilder.create() .disableAuthCaching() .disableAutomaticRetries() .disableCookieManagement() .disableRedirectHandling() .setDefaultSocketConfig(sockConf) .setSSLSocketFactory(sslSocketFactory) .setUserAgent(global.getAppName() + "/" + global.getAppVersion()) .build(); } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } }
public static String triggerHttpGetWithCustomSSL(String requestUrl) { String result = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }); @SuppressWarnings("deprecation") HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), hostnameVerifier); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpGet httpGet = new HttpGet("https://" + requestUrl); CloseableHttpResponse response = httpclient.execute(httpGet); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); log.debug("Received response: " + result); } else { log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode()); } } finally { response.close(); } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { log.error("Error executing the request.", e); } return result; }
@Test public void testCreate() throws KeyManagementException, NoSuchAlgorithmException { SSLContext sslContext = new SSLContextBuilder().build(); ClientOptions options = ClientOptions.builder() .setConnectionPoolSizePerRoute(2) .setConnectionPoolTotalSize(50) .setConnectTimeout(100) .setSocketTimeout(1000) .setRetryCount(5) .setSslContext(sslContext) .build(); assertEquals(2, options.getConnectionPoolSizePerRoute()); assertEquals(50, options.getConnectionPoolTotalSize()); assertEquals(100, options.getConnectTimeout()); assertEquals(1000, options.getSocketTimeout()); assertEquals(5, options.getRetryCount()); assertEquals(sslContext, options.getSslContext()); }
/** * custom http client for server with SSL errors * * @return */ public final CloseableHttpClient getCustomClient() { try { HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build(); builder.setSSLContext(sslContext); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); builder.setConnectionManager(connMgr); return builder.build(); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return getSystemClient(); }
private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { return HttpClients.custom(). setHostnameVerifier(new AllowAllHostnameVerifier()). setSslcontext(new SSLContextBuilder() .loadTrustMaterial(null, (arg0, arg1) -> true) .build()).build(); }
@Test public void contextLoads() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute?env=stage&key=PING", HttpMethod.GET, entity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals(new Integer(0), response.getBody().getCode()); Assert.assertNotNull(response.getBody().getOutput()); httpClient.close(); }
@Test public void hello() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute/hello", HttpMethod.GET, entity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
@Test public void executeCommands() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=DEPLOY&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Bounce() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=BOUNCE&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebmobile&env=dev", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Status() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=STATUS&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_NoKey() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<Object> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute", HttpMethod.POST, requestEntity, Object.class); Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
public void init() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); Unirest.setHttpClient(httpclient); } catch (Exception e) { System.out.println("Failed to start server: " + e.toString()); e.printStackTrace(); } }
private CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (cert != null) { for (X509Certificate chainCert : chain) { if (chainCert.equals(cert)) { return true; } } return false; } return true; } }).build(); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(factory).build(); } catch (GeneralSecurityException e) { logger.error(String.format("SSL connection create Fail : %s", e.getMessage())); } return HttpClients.createDefault(); }
CloseableHttpClient configureHttpClient(boolean enableSslVerify) { HttpClientBuilder builder = HttpClientBuilder.create(); if (enableSslVerify) { return builder.build(); } SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { LOG.error("Could not create ssl context", e); } builder.setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(sslContext); return builder.build(); }
@Test public void testWelcome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("welcome to the application "+System.getProperty("user.name"), entity.getBody()); }
/** * This creates a HTTP client instance for connecting the IFTTT server. * * @return the HTTP client instance */ private CloseableHttpClient buildHttpClient () { if ( configuration.isIftttIgnoreServerCertificate() ) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (Exception ex) { LOG.error(ex); // This should never happen, but we have to handle it throw new RuntimeException(ex); } } else { return HttpClients.createDefault(); } }
private void init() { biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); //Visit bilibili passport via https. 443 is the https port. biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); gson = ThreadLocal.withInitial(() -> new GsonBuilder() .setLenient() .create()); htmlUnitCache = ThreadLocal.withInitial(Cache::new); try { bilibiliSSLContext = SSLContextBuilder.create() .loadTrustMaterial(new BilibiliTrustStrategy()) .build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new AssertionError("failed initializing bilibili ssl context!"); } }
@Test public void sslDisabled() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); factory.setSsl(ssl); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); }
@Test public void sslGetScheme() throws Exception { // gh-2232 AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
protected final void testBasicSslWithKeyStore(String keyStore) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(null, "password", keyStore)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test(expected = IOException.class) public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); getResponse(getLocalUrl("https", "/test.txt"), requestFactory); }
@Test public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers)); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
private CloseableHttpClient getHttpsClient() { try { RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build(); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true ); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE ); return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory ) .build(); } catch ( Exception e ) { LOGGER.error( e.getMessage() ); } return HttpClients.createDefault(); }
/** * Allow SSL connections to utilize untrusted certificates * * @param httpClientBuilder * @throws MojoExecutionException */ private void configureInsecureSSL(HttpClientBuilder httpClientBuilder) throws MojoExecutionException { try { SSLContextBuilder sslBuilder = new SSLContextBuilder(); // Accept all Certificates sslBuilder.loadTrustMaterial(null, AcceptAllTrustStrategy.INSTANCE); SSLContext sslContext = sslBuilder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); httpClientBuilder.setSSLSocketFactory(sslsf); } catch (Exception e) { throw new MojoExecutionException("Error setting insecure SSL configuration", e); } }
public void setTrustedKeystore(final RestSettings.Keystore keystore) throws Exception { final SSLContextBuilder ssl = SSLContexts.custom(); final String path = keystore.getPath(); final String password = keystore.getPassword(); final URL resource = HttpClientFactoryBean.class.getClassLoader().getResource(path); if (resource == null) { throw new FileNotFoundException(format("Keystore [%s] not found.", path)); } try { ssl.loadTrustMaterial(resource, password == null ? null : password.toCharArray()); builder.setSSLSocketFactory(new SSLConnectionSocketFactory(ssl.build(), getDefaultHostnameVerifier())); } catch (final Exception e) { LOG.error("Error loading keystore [{}]:", path, e); // log full exception, bean initialization code swallows it throw e; } }
HttpPosterThread(LinkedBlockingQueue<String> lbq, String url) throws Exception { this.lbq = lbq; this.url = url; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); httpClient = HttpClients.custom().setSSLSocketFactory( sslsf).build(); //httpClient = HttpClientBuilder.create().build(); httpPost = new HttpPost(url); cntErr = 0; }