如何将Spring WebSocketClient与SSL一起使用?
作者:互联网
我将我的websocket客户端连接到非SSL端点没有任何问题.但我找不到如何连接到wss(SSL)端点的任何方法.我在哪里可以定义SSL工厂等.没有对象似乎有相关的set方法.
WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
String url = cfg.getWebsocketEndpoint();
StompSessionHandler handler = new MySessionHandler();
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
stompClient.connect(url, handler);
我使用的是wss:// url,另一方面我有一个带有自签名证书的服务器.但是,此代码在连接时不会抛出任何异常,但会话未建立.
编辑:启用网络跟踪.*我得到一个标准错误,用
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
使用自签名证书连接到服务器时会发生此问题.但是,对于RestTemplate,我已经使用此代码更新了SSLContext,现在REST调用很好,但我不知道为什么,StandardWebSocketClient是IGNORING SSLContext.为什么?
String keystoreType = "JKS";
InputStream keystoreLocation = new FileInputStream("src/main/resources/aaa.jks");
char [] keystorePassword = "zzz".toCharArray();
char [] keyPassword = "zzz".toCharArray();
KeyStore keystore = KeyStore.getInstance(keystoreType);
keystore.load(keystoreLocation, keystorePassword);
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, keyPassword);
InputStream truststoreLocation = new FileInputStream("src/main/resources/aaa.jks");
char [] truststorePassword = "zzz".toCharArray();
String truststoreType = "JKS";
KeyStore truststore = KeyStore.getInstance(truststoreType);
truststore.load(truststoreLocation, truststorePassword);
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(truststore);
KeyManager[] keymanagers = kmfactory.getKeyManagers();
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keymanagers, trustmanagers, new SecureRandom());
SSLContext.setDefault(sslContext);
更新:不幸的是,我没有设法使用自定义信任库.我使用InstallCert.java安装了证书.
解决方法:
我认为每个websocket容器实现都提供了执行此操作的方法.
您必须使用StandardWebSocketClient .setUserProperties设置此配置.所有这些属性都在客户端使用的ClientEndpointConfig内部设置.
以下是Tomcat作为提供者的示例:
StandardWebSocketClient wsClient = //...;
SSLContext sslContext = //...;
wsClient.setUserProperties(WsWebSocketContainer.SSL_CONTEXT_PROPERTY, sslContext);
在任何情况下,您都应该参考您的提供程序参考文档,以了解您应该使用哪些配置键.
标签:spring-websocket,spring,spring-boot,websocket 来源: https://codeday.me/bug/20191007/1865426.html