Search code examples
javaspringstompspring-websocket

How to limit client connections to my stomp websocket handler?


I need to keep track of users opening a websocket to my stomp broker in Spring 4.x. The stomp endpoint get configured the usual way:

@Configuration
@EnableWebSocketMessageBroker
public class StompWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/stomp");
  }

  @Override
  public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app")
            .enableSimpleBroker("/queue", "/topic");
  }

}

I tried to implement the ApplicationListener interface in order to receive SessionConnectEvent SessionConnectedEvent but I'm unable to get the remote host ip from those events.

How I'm supposed to get the ip of the client connecting to my service?

My goal is to limit the number of connections to my websocket handler from the same ip.


Solution

  • The way to do it is to customize the HandshakeHandler and overriding functions like isvalidOrigin.

    To add an HandshakeHandler using XML config a snippet like this one can be used:

      <bean id="customHandler" class="my.CustomWebsocketHandshakeHandler"/>
    
      <websocket:message-broker application-destination-prefix="/app">
        <websocket:stomp-endpoint path="/Stomp">
          <websocket:handshake-handler ref="customHandler"/>
        </websocket:stomp-endpoint>
        <websocket:simple-broker prefix="/topic,/queue" />
      </websocket:message-broker>
    

    I'm not able to produce the equivalent configuration using Java Config, though.

    I'll appreciate very much help on that subject