Reputation: 95
I need to validate somehow websocket requests.
Is there a way to achieve that using spring webflux with reactor-netty?
Upvotes: 2
Views: 2015
Reputation: 95
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);
}
Upvotes: 3