我需要以某种方式验证websocket请求。
有没有办法使用带有reactor-netty的spring webflux来实现这个目标?
这些版本包含使用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);
}