Spring Boot AsyncRestTemplate SSLSocketFactory

时间:2016-02-08 13:21:11

标签: java spring ssl apache-httpclient-4.x resttemplate

在WebSphere中部署Spring Boot应用程序。由于SSL配置,我们需要显式指定SSLSocketFactory以确保应用程序使用WebSphere证书而不是默认的Java密钥/信任存储。

通过RestTemplate这样做很简单:

protected RestTemplate getRestTemplate() {

    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(
        (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault(),
        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
    );

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme(HTTP_SCHEME, HTTP_PORT, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme(HTTPS_SCHEME, HTTPS_PORT, sslSocketFactory));

    BasicClientConnectionManager connectionManager = new BasicClientConnectionManager(registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);
    ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

    return new RestTemplate(requestFactory);
}

但是使用AsyncRestTemplate,我无法找到如何设置SSLSocketFactory:

protected AsyncRestTemplate getAsyncRestTemplate() throws IOReactorException, NoSuchAlgorithmException {

    SSLIOSessionStrategy strategy = new SSLIOSessionStrategy(
        SSLContext.getDefault(),
        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
    );

    Registry<SchemeIOSessionStrategy> registry = RegistryBuilder.<SchemeIOSessionStrategy>create()
        .register(HTTP_SCHEME, NoopIOSessionStrategy.INSTANCE)
        .register(HTTPS_SCHEME, strategy)
        .build();

    PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(
        new DefaultConnectingIOReactor(),
        registry
    );

    CloseableHttpAsyncClient httpClient = HttpAsyncClientBuilder
        .create()
        .setConnectionManager(connManager)
        .build();

    AsyncClientHttpRequestFactory requestFactory = new HttpComponentsAsyncClientHttpRequestFactory(httpClient);

    return new AsyncRestTemplate(requestFactory);
}

从本质上讲,我需要致电:

(javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault()

它触发WebSphere覆盖SSL连接处理。

非常感谢任何关于我所缺少的想法 - 谢谢。

1 个答案:

答案 0 :(得分:4)

你不能。 javax.net.SocketFactory与基于NIO的i / o模型不兼容。没有办法将SSLContext用于非阻止SSL。