authenticationwebsocketstomptorquebox

Authenticating stomp web socket clients


I have a ruby on rails application deployed to torquebox. I need some way to secure the websockets in my application. I am using the stomp websockets , is there a way to authenticate users while they make a websocket connection? I could use the username and password parameters but they are currently ignored. Is there any other way to authenticate this connection? Thanks!


Solution

  • You can authenticate a message to a Stomplet by using the session and a stored token. For this to work, you have to setup Rails to use the Torquebox session store. This can be done with an initializer, such as config/initializers/torquebox_init.rb:

    AppName::Application.config.session_store :torquebox_store
    

    Now the Stomplet will have access to the session. Here is an example Stomplet that uses the session param :authentication_token to match the User's authentication_token in the database. The auth token is checked for subscribing, sending a message, and unsubscribing:

    require 'torquebox-stomp'
    
    class StompletDemo
    
      def initialize()
        super
        @subscribers = []
      end
    
      def configure(stomplet_config)
      end
    
      def on_message(stomp_message, session)
        token = session[:authentication_token]
    
        if is_authenticated?( token )
          @subscribers.each do |subscriber|
            subscriber.send( stomp_message )
          end
        end
      end
    
      def on_subscribe(subscriber)
        session = subscriber.session
        if is_authenticated?(session[:authentication_token])
          @subscribers << subscriber
        end
      end
    
      def on_unsubscribe(subscriber)
        session = subscriber.session
        if is_authenticated?(session[:authentication_token])
          @subscribers.delete( subscriber )
        end
      end
    
      def is_authenticated?(token)
        User.where( authentication_token: token ).exists?
      end
    
    end
    

    Now all you have to do is make sure that when the user authenticates, the session[:authentication_token] is set. Mostly like this will be set in a controller:

     # user has successfully authenticates
     session[:authentication_token] = @user.authentication_token