|
| 1 | +package org.baeldung.client; |
| 2 | + |
| 3 | +import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; |
| 4 | +import static org.hamcrest.Matchers.equalTo; |
| 5 | +import static org.junit.Assert.assertThat; |
| 6 | + |
| 7 | +import java.security.GeneralSecurityException; |
| 8 | +import java.security.cert.X509Certificate; |
| 9 | + |
| 10 | +import org.apache.http.conn.scheme.Scheme; |
| 11 | +import org.apache.http.conn.ssl.SSLSocketFactory; |
| 12 | +import org.apache.http.conn.ssl.TrustStrategy; |
| 13 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 14 | +import org.junit.Test; |
| 15 | +import org.springframework.http.HttpMethod; |
| 16 | +import org.springframework.http.ResponseEntity; |
| 17 | +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; |
| 18 | +import org.springframework.web.client.RestTemplate; |
| 19 | + |
| 20 | +/** |
| 21 | + * This test requires a localhost server over HTTPS <br> |
| 22 | + * It should only be manually run, not part of the automated build |
| 23 | + * */ |
| 24 | +public class RestClientLiveManualTest { |
| 25 | + |
| 26 | + // tests |
| 27 | + |
| 28 | + @Test |
| 29 | + public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException() throws GeneralSecurityException { |
| 30 | + final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); |
| 31 | + final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient(); |
| 32 | + |
| 33 | + final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { |
| 34 | + @Override |
| 35 | + public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { |
| 36 | + return true; |
| 37 | + } |
| 38 | + }; |
| 39 | + final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER); |
| 40 | + httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf)); |
| 41 | + |
| 42 | + final String urlOverHttps = "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1"; |
| 43 | + final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); |
| 44 | + assertThat(response.getStatusCode().value(), equalTo(200)); |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments