CertificateException: No name matching localhost found using OAuth2RestTemplate NOT RestTemplate

Mick Knutson picture Mick Knutson · Nov 2, 2017 · Viewed 7.7k times · Source

I am trying to use a OAuth2RestTemplate to access a self-signed certificate to retrieve tokens over HTTPS but I am still getting this error:

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

This is my Unit test that is throwing the error:

    public class OAuth2ClientTest {

    private static final Logger logger = LoggerFactory
            .getLogger(SecurityConfig.class);

    @Value("${oauth.resource:https://localhost:8443}")
    private String baseUrl;

    @Value("${oauth.token:https://localhost:8443/oauth/token}")
    private String tokenUrl;

    @Value("${oauth.resource.id:microservice-test}")
    private String resourceId;

    @Value("${oauth.resource.client.id:client1}")
    private String resourceClientId;

    @Value("${oauth.resource.client.secret:changit}")
    private String resourceClientSecret;



    @Test
    public void execute_post_to_tokenUrl()
            throws ClientProtocolException, IOException {

        OAuth2RestTemplate template = template();

        ResponseEntity<String> response = template.exchange(
                tokenUrl,
                HttpMethod.POST,
                null,
                String.class);

        assertThat(response.getStatusCode().value(), equalTo(200));
    }

    private OAuth2RestTemplate template(){
        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setId(resourceId);
        resource.setClientId(resourceClientId);
        resource.setClientSecret(resourceClientSecret);

        resource.setGrantType("password");

        resource.setScope(Arrays.asList("openid"));

        resource.setUsername("[email protected]");
        resource.setPassword("user1");

        OAuth2RestTemplate template = new OAuth2RestTemplate(resource);

        ClientHttpRequestFactory factory = template.getRequestFactory();

        template.setRequestFactory(requestFactory());
        return template;
    }

    private HttpComponentsClientHttpRequestFactory requestFactory(){

        CloseableHttpClient httpClient
                = HttpClients.custom()
                .setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory
                = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        return requestFactory;
    }
}

When I use non-HTTPS connection, the OAuth2 code works fine. Just not with HTTPS

Answer

user2310395 picture user2310395 · Nov 20, 2017

You will have to create a certificate with alias "localhost" if you want TLS to work properly.
Other possibility is to set this somewhere statically or in your test configuration:

final HostnameVerifier defaultHostnameVerifier = javax.net.ssl.HttpsURLConnection.getDefaultHostnameVerifier ();
final HostnameVerifier localhostAcceptedHostnameVerifier = new javax.net.ssl.HostnameVerifier () {

   public boolean verify ( String hostname, javax.net.ssl.SSLSession sslSession ) {
        if ( hostname.equals ( "localhost" ) ) {
            return true;
        }
         return defaultHostnameVerifier.verify ( hostname, sslSession );
    }
};
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier ( localhostAcceptedHostnameVerifier );

...