Monday 19 November 2012

SSL using a RestEasy client

I had the misfortune today of having to figure out how to enable SSL for a REST client that uses the JBoss RestEasy client framework. This isn't really documented anywhere so I thought I'd make a note of it here.

Usually you would call your rest interface by doing something like this:


ServiceInterface myServiceClass  = (ServiceInterface)ProxyFactory.create(ServiceInterface.class,url);
What I found was if I tried to use a https URL this would fail with a 'PeerUnverified' exception as it (of course) doesn't trust the dodgy CA I used to issue my server certificate. In addition I want to provide client credentials so I can validate my identity when talking to the server. It turns out the way you do this is you provide a ClientExecutor object as the 3rd parameter to the ProxyFactory.create() method and this object is used to communicate with the server. It's a bit worse than that as you have to create a HttpConnection and then get the SchemeRegistry and add a mapping for https that uses a custom SSLSocketFactory. You create a SSLSocketFactory that knows about the KeyStore with your client credentials and your KeyStore in which your trusted CA cert lives. So anyway the code looks like this:
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(clientCreds,credentialsPass,trustStore); 

DefaultHttpClient httpClient = new DefaultHttpClient();ClientConnectionManager conManager = httpClient.getConnectionManager();
SchemeRegistry schemeRegistry = conManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https",8443,sslSocketFactory));  
ClientExecutor executor = ApacheHttpClient4Executor(httpClient);  

ServiceInterface myServiceClass = (ServiceInterface)ProxyFactory.create(ServiceInterface.class,url,executor);