rahulserver
rahulserver

Reputation: 11205

Ignore SSL errors with groovy's toURL method

I am trying to make http request using groovy's toURL() method in grails:

def holidayApiUrl = "https://holidayapi.com/v1/holidays?key=${apiKey}&year=2016&country=US"

def holidayJson = JSON.parse(holidayApiUrl.toURL().text)

You can get api keys from holidayapi.com to replicate this error.

Above request gives

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

So I was searching for ways to ignore ssl errors completely using this method in groovy. But not able to get it.

Other SO posts suggest things like this but groovy's toURL does not use SSLContext. So is it possible to ignore ssl errors using toURL()?

EDIT:

Anyone wanting to test above code fragment can signup free for holidaypi.com and get the api key. The url above (Replaced with api key) when hit in browser gives the proper json. But above code gives the SSL error when executed in groovy.

Upvotes: 6

Views: 9172

Answers (1)

Naeel Maqsudov
Naeel Maqsudov

Reputation: 1434

Just before you call

def holidayJson = new JsonSlurper().parse(holidayApiUrl)

Try to do the following (this creates and registers alternative TrustManager):

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HttpsURLConnection;

class TrustManager implements X509TrustManager {
  public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null;  }
  public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
  public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
}

TrustManager[] trustAllCerts = new TrustManager[1]
trustAllCerts[0] = new TrustManager()
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

Upvotes: 8

Related Questions