How to handle SSL self signed certificates with JAX-RS 2
To be able to accept a self-signed certificate with JAX-RS 2 Client API we need to build a SSLContext.
You can find how to build such an “unsecured” SSLContext over the internet and some of the class you need to implement for that are even part of some network libraries. Here is my version but feel free to write it the way you want:
final SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] x509Certificates, final String s) throws CertificateException {
// no-op
}
@Override
public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s) throws CertificateException {
// no-op
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new java.security.SecureRandom());
} catch (final NoSuchAlgorithmException | KeyManagementException e) {
throw new IllegalStateException(e);
}
We have a SSLContext, we now need to accept any host during host name verification phase. This one is pretty elegant using lambdas but you can also find implementations in several libraries (even in CXF):
final HostnameVerifier hostnameVerifier = (s, session) -> true;
Now we have a SSLContext and a HostnameVerifier so we need to set them on the client.
If you are used to the newClient() shortcut of JAX-RS Client API you will need to use the verbose version this time starting with the builder:
final Client client = ClientBuilder.newBuilder()
.hostnameVerifier((s, session) -> true)
.sslContext(sslContext)
.build()
Then you can create your WebTarget and Invocations and do your request even on untrusted self-signed certificates :).
From the same author:
In the same category: