Monday, July 6, 2009

Grails javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException No name matching

Recently I was trying to connect to a service via XMLRPC. The server had a cert that was invalid.
I tried the usual thing of importing the remote server cert into my JVM, restart my Grails client app and I still got the following error.

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching [server] found.

It happens because the server name and the name on the cert do not match. To get aorund this you have to turn the name validation off.

This is what you need to put in your Bootstrap.groovy to get around this.


def init = {servletContext ->
// Disable certificate verification
def trustManagerMethods = [
getAcceptedIssuers: { null },
checkClientTrusted: {a, b -> },
checkServerTrusted: {a, b -> }
]

def hostnameVerifierMethods = [
verify: {a, b -> true }
]

def trustManager = ProxyGenerator.instantiateAggregate(trustManagerMethods, [X509TrustManager])
TrustManager[] trustAllCerts = (TrustManager[]) [trustManager]

// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL")

def hostnameVerifier = ProxyGenerator.instantiateAggregate(hostnameVerifierMethods, [HostnameVerifier])
HostnameVerifier hv = (HostnameVerifier) hostnameVerifier

sc.init(null, trustAllCerts, new java.security.SecureRandom())
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
HttpsURLConnection.setDefaultHostnameVerifier(hv)
}