如何自定义websocket握手和/或添加过滤器?

时间:2018-09-17 14:41:19

标签: spring-boot websocket spring-websocket spring-webflux reactor-netty

我需要以某种方式验证websocket请求。

有没有一种方法可以使用带有反应器网络的spring webflux?

  • spring-boot 2.0.5。发布
  • 反应堆净值0.7.9。发布

1 个答案:

答案 0 :(得分:0)

这些版本包含使用websocket自定义内容的有限可能性。 我发现的唯一方法是扩展HandshakeWebSoketService:

public class CustomHandshakeWebSocketService extends HandshakeWebSocketService {

  public CustomHandshakeWebSocketService(
      RequestUpgradeStrategy upgradeStrategy
  ) {
    super(upgradeStrategy);
  }

  @Override
  public Mono<Void> handleRequest(
      ServerWebExchange exchange,
      WebSocketHandler handler
  ) {
    ServerHttpRequest request = exchange.getRequest();
    if ( //do some validation and if valid delegate to chain) {

      return super.handleRequest(exchange, handler);
    }
    // If not valid, return error
    return Mono
        .error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid request"));
  }
}

然后我们必须注册该定制服务:

@Bean
public WebSocketHandlerAdapter handlerAdapter() {
  return new WebSocketHandlerAdapter(webSocketService());
}

@Bean
public WebSocketService webSocketService() {
 ReactorNettyRequestUpgradeStrategy strategy = new ReactorNettyRequestUpgradeStrategy();
    return new CustomHandshakeWebSocketService(strategy);
}