在Spring Boot项目中,当使用spring-boot-starter-websocket
进行WebSocket通信时,我们通常会遇到与证书相关的问题,尤其是在代理连接时。出于安全和管理的考虑,有时我们需要在不引入第三方库的情况下,解决这些证书问题。
问题背景
在WebSocket代理连接的场景中,我们可能会碰到自签名证书或不受信任的证书。这些证书在默认情况下会被Java的SSL/TLS机制拒绝,导致连接失败。
解决方案
针对WebSocket代理连接时常见的证书问题,提供一个解决方案。尽管互联网上关于此类问题的现成解决方案较多,多数涉及引入如Java-WebSocket这样的第三方库,但在此,我将直接展示一种无需额外依赖的解决方法,并附上相应的代码实现。
本地环境:spring-boot 2.7.18 + 内置 tocmat 9.0.83
1. 导入官方的websocket
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 使用自定义的SSLContext配置WebSocket客户端
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.tomcat.websocket.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket
*/
@Configuration
@EnableWebSocket
public class SealosWebsocketConfig
{
@Bean
ServerEndpointExporter serverEndpoint()
{
return new ServerEndpointExporter();
}
/**
* 标准的客户端,并跳过证书
*
* @return
*/
@Bean
StandardWebSocketClient webSocketClient()
{
StandardWebSocketClient wsClient = new StandardWebSocketClient();
try {
// 跳过证书
SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(TrustAllStrategy.INSTANCE).build();
Map<String, Object> user = wsClient.getUserProperties();
user.put(Constants.SSL_CONTEXT_PROPERTY, sslContext);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
// 忽略
}
return wsClient;
}
}
3. 使用StandardWebSocketClient
@Autowired
private StandardWebSocketClient wsClient;
// ...
URI wsUri = new URI(wsUrl);
// ...
WebSocketSession se = wsClient.doHandshake(handler, headers, wsUri).get();
// ...
当使用StandardWebSocketClient
进行连接时,该客户端的内置机制能有效规避常见的证书问题。为了进一步提升安全性或适配特定的网络环境,您还可以配置自定义的证书,比如自签名证书。此外,为了满足不同场景下的需求,StandardWebSocketClient
还支持对额外的配置信息进行灵活修改。下面是相关操作的底层核心源码示例:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.websocket;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
import javax.websocket.ClientEndpoint;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.Extension;
import javax.websocket.HandshakeResponse;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.InstanceManagerBindings;
import org.apache.tomcat.util.buf.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.collections.CaseInsensitiveKeyMap;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.KeyStoreUtil;
public class WsWebSocketContainer implements WebSocketContainer, BackgroundProcess {
private static final StringManager sm = StringManager.getManager(WsWebSocketContainer.class);
private static final Random RANDOM = new Random();
private static final byte[] CRLF = new byte[] { 13, 10 };
private static final byte[] GET_BYTES = "GET ".getBytes(StandardCharsets.ISO_8859_1);
private static final byte[] ROOT_URI_BYTES = "/".getBytes(StandardCharsets.ISO_8859_1);
private static final byte[] HTTP_VERSION_BYTES = " HTTP/1.1\r\n".getBytes(StandardCharsets.ISO_8859_1);
private volatile AsynchronousChannelGroup asynchronousChannelGroup = null;
private final Object asynchronousChannelGroupLock = new Object();
private final Log log = LogFactory.getLog(WsWebSocketContainer.class); // must not be static
// Server side uses the endpoint path as the key
// Client side uses the client endpoint instance
private final Map<Object, Set<WsSession>> endpointSessionMap = new HashMap<>();
private final Map<WsSession, WsSession> sessions = new ConcurrentHashMap<>();
private final Object endPointSessionMapLock = new Object();
private long defaultAsyncTimeout = -1;
private int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE;
private int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE;
private volatile long defaultMaxSessionIdleTimeout = 0;
private int backgroundProcessCount = 0;
private int processPeriod = Constants.DEFAULT_PROCESS_PERIOD;
private InstanceManager instanceManager;
protected InstanceManager getInstanceManager(ClassLoader classLoader) {
if (instanceManager != null) {
return instanceManager;
}
return InstanceManagerBindings.get(classLoader);
}
protected void setInstanceManager(InstanceManager instanceManager) {
this.instanceManager = instanceManager;
}
@Override
public Session connectToServer(Object pojo, URI path) throws DeploymentException {
ClientEndpointConfig config = createClientEndpointConfig(pojo.getClass());
ClientEndpointHolder holder = new PojoHolder(pojo, config);
return connectToServerRecursive(holder, config, path, new HashSet<>());
}
@Override
public Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException {
ClientEndpointConfig config = createClientEndpointConfig(annotatedEndpointClass);
ClientEndpointHolder holder = new PojoClassHolder(annotatedEndpointClass, config);
return connectToServerRecursive(holder, config, path, new HashSet<>());
}
private ClientEndpointConfig createClientEndpointConfig(Class<?> annotatedEndpointClass)
throws DeploymentException {
ClientEndpoint annotation = annotatedEndpointClass.getAnnotation(ClientEndpoint.class);
if (annotation == null) {
throw new DeploymentException(
sm.getString("wsWebSocketContainer.missingAnnotation", annotatedEndpointClass.getName()));
}
Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = annotation.configurator();
ClientEndpointConfig.Configurator configurator = null;
if (!ClientEndpointConfig.Configurator.class.equals(configuratorClazz)) {
try {
configurator = configuratorClazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new DeploymentException(sm.getString("wsWebSocketContainer.defaultConfiguratorFail"), e);
}
}
ClientEndpointConfig.Builder builder = ClientEndpointConfig.Builder.create();
// A