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)
}

3 comments:

simo said...

Thanks! It really helped me with this issue.
Remember to add

import javax.net.ssl.*

to get it to work correctly.

sadhna said...

thanks Simo & Vijay. your post really helped me. but i am getting this error while calling a https webservice-
"Error during SSL handshake between client and server. If you enabled client authentication for the server, then you must pass keystore parameters to the client"

Please advice.
Sadhna

Philip Wu said...

Fast-forward 8 years later, and this technique still works on Grails 3. Many thanks