Bypass SSL Certificate Checking in Java

To disable or bypass SSL certificate checking is never a recommended solution for SSL issues, but at test environment – sometimes you may need this. In this tutorial, I am creating instances of org.apache.http.impl.client.DefaultHttpClient available till Apache HTTP Library version 4.2 and org.apache.http.impl.client.CloseableHttpClient available since Apache HTTP Library version 4.3.

DefaultHttpClient is a deprecated class now, so it’s suggested to use CloseableHttpClient class. Please remember to bypass the SSL checking only for debug purposes when we want to test a few secured APIs without setting up installing the certificate on the local machine.

1. Bypass SSL Certificate Checking using CloseableHttpClient

If you are working with the latest versions of the apache HTTP library, you should this version of the code.

public static CloseableHttpClient getCloseableHttpClient()
{
	CloseableHttpClient httpClient = null;
	try {
		httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
		        .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
		        {
		            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
		            {
		                return true;
		            }
		        }).build()).build();

	} catch (KeyManagementException e) {
		LOGGER.error("KeyManagementException in creating http client instance", e);
	} catch (NoSuchAlgorithmException e) {
		LOGGER.error("NoSuchAlgorithmException in creating http client instance", e);
	} catch (KeyStoreException e) {
		LOGGER.error("KeyStoreException in creating http client instance", e);
	}
	return httpClient;
}

To use CloseableHttpClient instance, use it in the below manner.

//Some custom method to craete HTTP post object
HttpPost post = createPostRequest(); 

//Get http client
CloseableHttpClient httpClient = getCloseableHttpClient();

//Execute HTTP method
CloseableHttpResponse res = httpClient.execute(post);

//Verify response
if(res.getStatusLine().getStatusCode() == 200)
{
	String json = EntityUtils.toString(res.getEntity());
}

2. Bypass SSL Certificate Checking using DefaultHttpClient

If you are working on older versions of the apache HTTP library, you should this version of the code.

public static DefaultHttpClient getDefaultHttpClient() throws Exception
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	SSLContext ssl_ctx = SSLContext.getInstance("TLS");
	TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public void checkClientTrusted(X509Certificate[] certs, String t) {
		}

		public void checkServerTrusted(X509Certificate[] certs, String t) {
		}
	} };
	ssl_ctx.init(null, certs, new SecureRandom());
	SSLSocketFactory ssf = new SSLSocketFactory(ssl_ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	ClientConnectionManager ccm = httpClient.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));
	return new DefaultHttpClient(ccm, httpClient.getParams());
}

To use DefaultHttpClient instance, use it in the below manner.

//Some custom method to craete HTTP post object
HttpPost post = createPostRequest(); 

//Get http client
DefaultHttpClient client = getDefaultHttpClient();

//Execute HTTP method
HttpResponse httpResponse = client.execute(post);

//Handle response

Once again, please do not use it on production environment because it defeats the whole purpose of having SSL security on first place.

3. Configure Spring RestTemplate

If we use this code in a Spring application, we can configure the RestTemplate bean in the following manner. Do not forget to comment out this code when moving to production.

@Configuration
public class RestTemplateSSLBypassConfig {
 
	@Bean
	public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    		TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
 
    		SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    		.loadTrustMaterial(null, acceptingTrustStrategy)
                    		.build();
 
    		SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
 
    		CloseableHttpClient httpClient = HttpClients.custom()
                    		.setSSLSocketFactory(csf)
                    		.build();
 
    		HttpComponentsClientHttpRequestFactory requestFactory =
                    		new HttpComponentsClientHttpRequestFactory();
 
    		requestFactory.setHttpClient(httpClient);
    		RestTemplate restTemplate = new RestTemplate(requestFactory);
   		return restTemplate;
 	}
}

4. Configure Spring WebClient

We can also configure a WebClient that uses the insecure InsecureTrustManagerFactory as follows:

@Bean
public WebClient createWebClient() throws SSLException {
    SslContext sslContext = SslContextBuilder
            .forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();
    HttpClient httpClient = HttpClient.create().secure(t -> t.sslContext(sslContext));
    return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build();
}

5. Possible Exception Message of SSLHandshakeException

If you have not set up the above code correctly, you may find the exception message below. This message confirms that SSL certificate matching is still failing.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1916)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1472)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:213)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:913)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:849)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1035)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1344)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
	at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
	at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)

Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode