I need to control connection/disconnection and subscriptions/unsubscriptions of stomp clients in my websocket spring server. This is the main configuration class:
@Configuration
@ComponentScan(basePackages = "com.test")
@EnableWebSocketMessageBroker
@EnableWebMvc
public class Config extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue", "/topic");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").setAllowedOrigins("*").addInterceptors(getInterceptot());
}
private HandshakeInterceptor getInterceptot() {
return new HandshakeInterceptor(){
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
return true; //TODO
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {}
};
}
}
I could intercept the connection event with beforeHandshake
method, but I don't know if this is the best way.
Moreover I need to check all disconnections, subscription and unsubscriptions, I tried to use @SubscribeMapping("/**")
annotation but it doesn't work for me.
I tried this:
@Component
public class StompEventListener {
@EventListener
private void handleSessionConnected(SessionConnectEvent event) {
}
@EventListener
private void handleSessionDisconnect(SessionDisconnectEvent event) {
}
@EventListener
private void handleSessionSubscribeEvent(SessionSubscribeEvent event) {
}
@EventListener
private void handleSessionUnsubscribeEvent(SessionUnsubscribeEvent event) {
}
}
It works, but I need to intercept this request and I should deny/grant all operations, for example I can decide to deny the connection but with @EventListener
I cannot do this because it is called after the connection.