javassljava-securitynimbus-jose-jwt

How to disable Host name verification for nimbus JWKS ResourceRetriever


First I was using 'DefaultResourceRetriever' without any configuration like this :

new DefaultResourceRetriever(1000, 1000);

and then I got the following exception

java.security.cert.CertificateException: No subject alternative DNS name matching my-jwks-url.com found.

To by pass certificate check I have configured the resource retriever like below;

TrustStrategy trustStrategy = (X509Certificate[] x509Certificates, String s) -> true;

SSLContext sslContext = SSLContexts.custom()
    .loadTrustMaterial(null, trustStrategy)
    .build();

SSLSocketFactory socketFactory = sslContext.getSocketFactory();

return new DefaultResourceRetriever(1000, 1000, 0, true, socketFactory);

But it doesn't changed anything.

I could set Hostname verifier to SSLConnectionSocketFactory like this:

new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()) But nimbus ResourceRetriever only accept SSLSocketFactory as a parameter.

Is there any way to disable Hostname verification?


Solution

  • I resolved it by extending DefaultResourceRetriever and overriding openConnection(URL url) method.

    If URL is HTTPS, it creates HttpsURLConnection. And we can set NoopHostnameVerifier to it.

    Here is my solution :

    public class NoopHostnameVerifyingResourceRetriever extends DefaultResourceRetriever {
        
          public NoopHostnameVerifyingResourceRetriever(int connectTimeout, int readTimeout) {
            super(connectTimeout, readTimeout);
          }
        
          @Override
          protected HttpURLConnection openConnection(URL url) throws IOException {
            HttpURLConnection connection = super.openConnection(url);
        
            if (connection instanceof HttpsURLConnection) {
              ((HttpsURLConnection) connection).setHostnameVerifier(new NoopHostnameVerifier());
            }
        
            return connection;
          }
    }