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

问题描述 投票:0回答:1

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

有没有办法使用带有reactor-netty的spring webflux来实现这个目标?

  • spring-boot 2.0.5。发布
  • reactor-netty 0.7.9。发布
spring-boot websocket spring-websocket spring-webflux reactor-netty
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.