How to customize websocket handshake and/or add a filter?

Viewed 1083

I need to validate somehow websocket requests.

Is there a way to achieve that using spring webflux with reactor-netty?

  • spring-boot 2.0.5.Release
  • reactor-netty 0.7.9.Release
1 Answers

These versions contain limited possibilities to customize something with websocket. The only way that I found is to extend 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"));
  }
}

Then we have to register that custom service:

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

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