目录
WebSocket是一种在单个TCP连接上进行全双工通信的协议。它使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。浏览器只需要和服务端完成一次握手,两端就可以建立持久性链接来进行双向通信。但在实际的应用中为了防止恶意的未经授权的客户端发起链接,此时就需要客户端在与服务端建立链接时携带指定的授权信息,服务端在响应握手时对携带的授权协议信息进行鉴权,校验成功后方可放行从而握手成功建立长链接。那么对于websocket无法携带header 信息和cookie我们该如何向服务端传输授权信息进而鉴权呢(如:自定义token,jwt,用户账号信息等),看下文分解。
一、springboot+websocket搭建
1.1.使用依赖
// gradle
implementation 'org.springframework.boot:spring-boot-starter-websocket'
// maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
1.2.WebSocketInterceptor鉴权拦截器
鉴权逻辑将在这里做,待下文分解
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
/**
* 日志
*/
private static final Logger log = LoggerFactory.getLogger(WebSocketInterceptor.class);
/**
* 握手之前
*
* @param request request
* @param response response
* @param wsHandler handler
* @param attributes 属性
* @return 是否握手成功:true-成功,false-失败
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) {
//这里做客户端鉴权业务处理,下文分解
return true;
}
/**
* 握手后
*
* @param request request
* @param response response
* @param wsHandler wsHandler
* @param exception exception
*/
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
log.info("handshake success!");
}
}
1.3.MyWebSocketHandler处理器
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class MyWebSocketHandler extends TextWebSocketHandler {
/**
* 日志
*/
private static final Logger log = LoggerFactory