我需要以某种方式验证websocket请求。
有没有一种方法可以使用带有反应器网络的spring webflux?
答案 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);
}